89DEVs

How to print a float with two decimal places in Python?

How to print a float with two decimal places in Python?

To print a float with two decimal places in Python, use the format() method of strings or the round() function.

format() function

Use the format() function as shown below, to print a float with two decimal places. # print a float with two decimal places using the format() method myFloat = 3.14159 myFormatedFloat = "{:.2f}".format(myFloat) print(myFormatedFloat) First a float with 5 decimal places is defined as an example value. Then the float is formatted using the format() method of string. The float value is returned with 2 decimal places. 3.14

round() function

Another approach to print a float with two decimal places, is to use the round() function as shown below. # print a float with two decimal places using the round() function myFloat = 3.14159 myRoundedFloat = round(myFloat, 2) print(myRoundedFloat) First the same float value as above is assigned to the myFloat variable as an example to demonstrate the round() function. Then, round() is used to round the float value to two decimal places. As first argument the float is passed to the round() function. As second argument the number of decimal places is specified, in this case 2 decimal places are wanted. Finally, the rounded float is printed and the result is shown below. 3.14

                
        

Summary


Click to jump to section