Python 中关于 round 函数的小坑


遇到的小坑,round(10.5)得到的结果是10,很疑惑,查了一下资料,总结一下:

round的结果跟python版本有关

这是Python 2:

1
2
3
4
5
6
$ python
Python 2.7.8 (default, Jun 18 2015, 18:54:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
1.0

这是Python3:

1
2
3
4
5
6
$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
0

为什么?

看一下文档:

Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0.

这是Python2.7的文档,可以看到这里是真正意义上的四舍六入。但到了Python3就变成了这样:

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.

此时,如果距离两边一样远,会保留到偶数的一边。比如round(0.5)round(-0.5)都会保留到0,而round(1.5)会保留到2