89DEVs

Python: How to control float precision?

How to control float precision in Python?

To control float precision in Python, use the format() method of strings or the round() function.

format() method

To control the float precision of decimals, use the format method as shown below. # control float precision using format() method myFloat = 3.14159 myFormatedFloat = "{:.2f}".format(myFloat) print(myFormatedFloat) Limit float precision to two decimals. 3.14

round() function

Use the round() function as shown below, to control the float precision of decimals. # control float precision using round() function myFloat = 3.14159 myRoundedFloat = round(myFloat, 1) print(myRoundedFloat) In this example the same float value as in the example above is assigned to the variable myFloat. Then the round() function is used and the variable is passed as first argument. As second argument the integer 1 is passed, to specify the number of decimal places. Finally, the rounded float value is printed and the result is shown below. 3.1

                
        

Summary


Click to jump to section