Round rounding details -- difference between python2 and python3 the round () method returns the decimal point rounded to n numbers.
Syntax
The syntax of the round () method is as follows:
Round (x [, n])
Parameters
X -- this is a value, indicating the value to be formatted
N -- this is also a value, indicating the number of digits after the decimal point
Return value
This method returns the number x rounded to n decimal places.
PS: round rounds the incoming data. if ngigits is not transmitted, the default value is 0 (that is, the integer part is retained ). when ngigits is <0, it is used to round the integer part. the returned result is a floating point number.
Example
The following example shows how to use the round () method.
#!/usr/bin/python2print "round(80.23456, 2) : ", round(80.23456, 2)print "round(100.000056, 3) : ", round(100.000056, 3)print "round(-100.000056, 3) : ", round(-100.000056, 3)
When we run the above program, it will produce the following results:
round(80.23456, 2) : 80.23round(100.000056, 3) : 100.0round(-100.000056, 3) : -100.0
Differences between Python 3 and Python 2
Python2 rounds x to the nearest multiple away from 0, for example, round (0.5) = 1, round (-0.5) =-1;
Python3 rounds x to the nearest even multiple, for example, round (0.5) = 0, round (1.5) = 2.0, round (2.5) = 2.0
Code:
#!/usr/bin/python2print round(2.635, 2)print round(2.645, 2)print round(2.655, 2)print round(2.665, 2)print round(2.675, 2)
Output result:
2.632.652.652.672.67
Round method defects
Through the above example, we can find that the rounding method of the round seems to be different from what we understand. In fact, this is not a bug in the round. this is mainly from the conversion of decimal to binary inside the computer during input, this problem cannot be solved with limited precision, and does not need to be solved.
The decimal module of Python can be used to solve this problem.
If you do not need to rounding it up, you can also consider using the print ("%. 2f" % 2.675) method we are most familiar.