← Go Back
A second argument indicates the number of digits after the point with respect to which the approximation should be made.
Note that when the last digit is 5, the function does not round up but returns the nearest even number:
If you want to round up, use the following function instead:
How to Round a Number
Theround()
built-in function takes a floating point number and returns an integer according to the rounding rules.>>> round(1.4)
1
>>> round(1.5)
2
A second argument indicates the number of digits after the point with respect to which the approximation should be made.
>>> round(1,539, 2)
1.54
Note that when the last digit is 5, the function does not round up but returns the nearest even number:
>>> round(1.5)
2
>>> round(2.5) # Typically 3 would be expected.
2
If you want to round up, use the following function instead:
import math
# Source: https://stackoverflow.com/a/52617883/2116607
def custom_round(n: float, decimals: int = 0) -> float:
expoN = n * 10 ** decimals
if abs(expoN) - abs(math.floor(expoN)) < 0.5:
return math.floor(expoN) / 10 ** decimals
return math.ceil(expoN) / 10 ** decimals
print(custom_round(1.5)) # 2
print(custom_round(2.5)) # 3
print(custom_round(1.535, 2)) # 1.54
🐍 You might also find interesting: