How to round to 2 decimals?
Use the built-in round() function in Python to round to 2 decimal places. The round() in function accepts two arguments. The first one the value to be rounded and the second one to specify the number of decimals to round.
# round to 2 decimal places
myFloat = 2.4444
rounded = round(myFloat, 2)
print(rounded)
As expected the round() function returns a float with 2 decimal places. In this case 2.44.
2.44
round to 3 or more decimal places
To round to 3 or more decimal places, adjust the second argument of the round function.
# round to 3 or more decimal places
myFloat = 2.444444444444
rounded_3_decimals = round(myFloat, 3)
rounded_4_decimals = round(myFloat, 4)
rounded_5_decimals = round(myFloat, 5)
print('rounded to 3 decimals', str(rounded_3_decimals))
print('rounded to 4 decimals', str(rounded_4_decimals))
print('rounded to 5 decimals', str(rounded_5_decimals))
The float value is rounded to the number of digits defined in the second argument of the round() function.
rounded to 3 decimals 2.444
rounded to 4 decimals 2.4444
rounded to 5 decimals 2.44444
trailing zeros are truncated
The round() function might return some surprising results. For example, trailing zeros are truncated.
# round to 2 decimal places
myFloat = 2.99999
rounded = round(myFloat, 2)
print(rounded)
The round() function returns 3.0 and truncates the second decimal place even though we specified it in the second argument.
3.0
limitations
Another surprising behavior of the round() function can be seen by rounding 2.675 to 2 decimals.
# round to 2 decimal places
myFloat = 2.675
rounded = round(myFloat, 2)
print(rounded)
Instead of the expected 2.68 the round() function returns 2.67.
2.67
This is not a bug, rather a limitation of the float type. Since most decimal fractions cannot be represented exactly as binary fractions. It is important to be aware of the limitations.
other rounding operations in Python
Python offers a variety of other rounding operations:
To round up use math.ceil() or numpy.ceil() methods.
To round down use the int() function or the math.floor() method.
To round to nearest integer use the round() function or numpy.round().
To round to 5 (or any other number) use a custom function.