Python3 round() Function

Python3 数字Python3 Numbers


Description

round()The method returns the rounded value of the floating-point number x. To be precise, the retained value will be kept to the side closer to the previous digit (round half to even).

If high precision is required, this function is not recommended.


Syntax

The following is the syntax for the round() method:

round( x [, n]  )

Parameters

  • x -- A numeric expression.
  • n -- Indicates the number of digits from the decimal point, where x needs to be rounded; the default value is 0.

Return Value

Returns the rounded value of the floating-point number x.

Examples

The following shows an example of using the round() method:

Examples

#!/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 example after running 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

Take a look at an example given on the official website:

>>> round(2.675, 2) 
2.67

According to our thinking, the returned result should be 2.68, but the result is 2.67. Why?

This is related to the precision of floating-point numbers. We know that in a machine, floating-point numbers may not be represented exactly, because after converting to a string of 1s and 0s, it may have infinite digits, and the machine has already truncated it. So the number 2.675 stored in the machine is a little smaller than the actual number. This tiny difference causes it to be a little closer to 2.67, so when keeping two decimal places, it is approximated to 2.67.

Python3 数字Python3 Numbers

Other Extensions