Python3 round()
Function
Description
The round() method returns the rounded value of the floating-point number x, accurately preserving the value closer to the nearest integer (rounding half to even).
For high precision requirements, it is not recommended to use this function.
Syntax
The syntax for the round() method is as follows:
round( x [, n] )
Parameters
x -- A numeric expression.
n -- Represents the number of decimal places, where x needs to be rounded. The default value is 0.
Return Value
Examples
Below are examples demonstrating the use of the round() method:
#!/usr/bin/python3
print("round(70.23456) : ", round(70.23456))
print("round(56.659,1) : ", round(56.659,1))
print("round(80.264, 2) : ", round(80.264, 2))
print("round(100.000056, 3) : ", round(100.000056, 3))
print("round(-100.000056, 3) : ", round(-100.000056, 3))
The output of the above examples is:
round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
Consider an example from the official documentation:
>>> round(2.675, 2)
2.67
Why does our expected result of 2.68 return as 2.67?
This is related to the precision of floating-point numbers. We know that floating-point numbers may not be precisely represented in machines because they might convert to an infinite sequence of 1s and 0s, which the machine truncates. The number 2.675 stored in the machine is slightly smaller than the actual number. This slight difference makes it closer to 2.67, so when rounded to two decimal places, it approximates to 2.67.