python: round 内建函数 (四舍五入)

Syntax

round(number[, ndigits=0])

number 进行 四舍五入

Args :

  • number :可正可负 。
  • ngigits :保留 ngigits 位 小数

Test

assert round(0.5) == 1.0
assert round(-0.5) == -1.0

assert round(12345.678, -5) == 0.0
assert round(12345.678, -4) == 10000.0
assert round(12345.678, -3) == 12000.0
assert round(12345.678, -2) == 12300.0
assert round(12345.678, -1) == 12350.0
assert round(12345.678, 0) == 12346.0 == round(12345.678)
assert round(12345.678, 1) == 12345.7
assert round(12345.678, 2) == 12345.68
assert round(12345.678, 3) == 12345.678
assert round(12345.678, 4) == 12345.6780

round 陷阱

举例

print round(1.045, 2)
print round(1.055, 2)

打印结果:

1.04
1.05

原因

见 Python 为什么不解决四舍五入(round)的“bug”? 。



你可能感兴趣的:(Python,编程)