Display a float with two decimal places in Python
In this tutorial, you will learn how to display a float with two decimal places in Python. You can also display one decimal place or more than two decimal places, this methods are called precision handling in Python. We use rounding methods to display float numbers with particular decimal places.
Rounding methods:
- round(): It is a function used in the rounding method that rounds the value into the required decimal places or the nearest value.
- format(): It is a method used to display a float value into a particular decimal place using f-string syntax.
Code for round() method:
n=float(input("Enter a float value:")) round_value = round(n, 2) print("Rounded value using round:", round_value)
Output 1:
Enter a float value:3.412 Rounded value using round: 3.41
output 2:
Enter a float value:2.9999 Rounded value using round: 3.00
Explanation:
This round() is used to round the given float value into a particular decimal place. This method can round the entire value, as shown in output 2. From output 1, the value is directly rounded to two decimal places. Using the round() method, we can round the values to one decimal place, two decimal places, three decimal places, four decimal places, and more by changing the digit in the round(n , digit).
Code for format() method:
n=float(input("Enter a float value : ")) round="{:.2f}".format(n) print("Float value using format :", round)
Output 1:
Enter a float value : 2.6661 Float value using the format: 2.66
Output 2:
Enter a float value : 10.9999 Float value using the format : 11.00
Explanation:
The format() method in Python is used to display a float number with a decimal place or a number as shown in output 2. Here in the format() method we use f-string syntax to display the float value with the required decimal place, they are {:.1f}, {:.2f}, {:.3f}, {:.4f}, etc. If you want to display three decimal places of a float number, you can use {:.3f} syntax. So, it will display the float value with three decimal places.
Leave a Reply