Python内置函数(55)——round

时间:2022-07-03 05:16:09

英文文档:

round(number[, ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it returns the nearest integer to its input. Delegates to number.__round__(ndigits).
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.
Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

说明:

  1. round函数用于对浮点数进行四舍五入求值,具体保留几位小数,以传入的ndigits参数来控制。

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149

  2. ndigits参数为可选参数,当不传入时,即以默认保留0位小数进行取整,返回的是整数。

>>> round(1.1314926)
1

  3. ndigits参数传入0时,虽然与不传入ndigits参数一样保留0位小数进行四舍五入,但是返回的值是浮点型。

>>> round(1.1314926,0)
1.0

  4. ndigits参数小于0时,对整数部分进行四舍五入,ndigits参数控制了对浮点数的整数部分的后几位进行四舍五入,小数部分全部清0,返回类型是浮点数。如果传入的浮点数的整数部分位数小于ndigits参数绝对值,则返回0.0.

>>> round(11314.926,-1)
11310.0
>>> round(11314.926,-3)
11000.0
>>> round(11314.926,-4)
10000.0
>>> round(11314.926,-5)
0.0

  5. round四舍五入时是遵循靠近0原则,所以-0.5和0.5进行0位四舍五入,返回的都是0.

>>> round(0.5)
0
>>> round(-0.5)
0

  6. 对于浮点数求四舍五入有一个陷阱,有些四舍五入结果不像预期那样,比如round(2.675, 2) 的结果是2.67 而不是预期的 2.68,这不是bug,而是浮点数在存储的时候因为位数有限,实际存储的值和显示的值有一定误差。

>>> round(2.675, 2)
2.67

  7. 对整数也能进行round操作,返回值也是整形。

>>> round(134567)
134567
>>> round(134567,0)
134567
>>> round(134567,1)
134567
>>> round(134567,2)
134567
>>> round(134567,-2)
134600
>>> round(134567,-6)
0