How to round float values in Python

You can round a float number in several ways using python. In this post we will cover:

  • (round(x, y) - Python round float numbers N decimal points
  • '{0:.{1}f}'.format(x, y) - Python round by using format
  • int(round(x)) - round to integer

Python round float numbers N decimal points

We can round float number in python by using round() which is a built-in function. It will round number x rounded to y decimal points.

Examples:

x = 42.19842018
print("round(x) : ", round(x))
print("round(x,1) : ", round(x, 1))
print("round(x, 2) : ", round(x, 2))

result:

round(x) :  42
round(x,1) :  42.2
round(x, 2) :  42.2

Python round by using format

You can use function format if you want to round floats. Below you can find several examples:

  • format(x, 1) - round 1 decimal point
  • format(x, 2) - round decimal point
  • " {0:11.3f} ".format(x)) - round 3 decimal point and format the number in 11 characters

Examples:

x = 42.19842018
print("Function format 3 decimal places {0:11.3f} ".format(x))
print('{0:.{1}f}'.format(x, 1))
print('{0:.{1}f}'.format(x, 2))

result:

Function format 3 decimal places      42.198 
42.2
42.20

Python round to integer - int(round(x))

If you want to round your float number to integer you can use this example:

x = 42.19842018
print(round(x, 0))
print(int(round(x)))

result:

42.0
42

Related Article