The round () method returns the decimal point of a numeric value rounded to n digits.
Grammar
The following is the syntax for the Round () method:
Round (x [, N])
Parameters
X-This is a numeric value that represents the value that needs to be formatted
N-This is also a numeric value that indicates how many digits are retained after the decimal point
return value
The method returns the decimal point of the value x rounded to n digits
Ps:round rounds the incoming data, and if Ngigits does not, the default is 0 (that is, preserve the integer portion). ngigits<0 is the time to round the integer part, and the result is a floating-point number.
Example
The following example shows the use of the round () method
#!/usr/bin/python2print "Round (80.23456, 2):", Round (80.23456, 2) print "Round (100.000056, 3):", Round (100.000056, 3) PR int "Round ( -100.000056, 3):", round (-100.000056, 3)
When we run the above program, it produces the following results:
Round (80.23456, 2): 80.23round (100.000056, 3): 100.0round (-100.000056, 3):-100.0
Differences between the Python3 and Python2 versions
Python2 x rounded to the nearest multiple of 0, such as round (0.5) =1, round (-0.5) =-1;
Python3 rounds X to the nearest even number of times, such as 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 round rounding method seems to be different from what we understand, in fact, this is not a round bug, this is mainly from the input decimal conversion to the computer internal binary, and this problem in the limited precision can not be solved, also do not need to solve.
The Python decimal module can be used to solve this problem.
If you do not need to round up, you can also consider using our most familiar print ("%.2f"% 2.675) to achieve this way.