赞
踩
round()取整
使用round()函数可以轻松的对浮点数进行取整操作。示例如下:
>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-0.36, 1)
-0.4
round()第二个参数可以是负数:
>>> a = 13849
>>> round(a, -1)
12850
>>> round(a, -2)
13800
但是要注意,这里有两个很奇怪的例子:
>>> round(2.5)
2
>>> round(0.5)
0
可以发现,这里完全没有按照我们所熟悉的四舍五入的取整规则来。这是因为round()函数在应对这种与两个整数距离相同的情况时,会取到最近的偶数上去。
同时官方文档中还举了一个例子,
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 Arithme
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。