Python3 round() Function
Description
round() The method returns the rounded value of float x; more precisely, the retained value is the end closer to the preceding digit (round half to even).
It is not recommended for cases requiring high precision.
Syntax
The syntax of the round() method is as follows:
round( x [, n] )
Parameters
- x -- a numeric expression.
- n -- the number of decimal places to which x is rounded, defaulting to 0.
Return Value
Returns the rounded value of float x.
Example
The following shows examples of using the round() method:
Example
#!/usr/bin/python3
(
"round(70.23456) : "
,
round
(
70.23456
)
)
(
"round(56.659,1) : "
,
round
(
56.659
,
1
)
)
(
"round(80.264, 2) : "
,
round
(
80.264
,
2
)
)
(
"round(100.000056, 3) : "
,
round
(
100.000056
,
3
)
)
(
"round(-100.000056, 3) : "
,
round
(
100.000056
,
3
)
)
Running the example above produces:
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
Take a look at an example from the official documentation:
>>> round(2.675, 2)
2.67
In our expectation the result should be 2.68, but it is 2.67. Why?
This is related to floating-point precision. We know that in a machine a float may not be represented exactly, because when converted into a string of 1s and 0s it may have infinitely many digits, and the machine truncates it. So the number 2.675 stored in the machine is slightly smaller than the actual number. That tiny difference makes it slightly closer to 2.67, so rounding to two decimal places gives 2.67.
Python3 Numbers