Python 3:内置的round(...)函数表现得很奇怪。 Python 3中Python 2的替代方案?

时间:2014-08-06 23:01:53

标签: python math python-3.x rounding

Python 3

>>> round(1.5)
2
>>> round(2.5)
2
>>> round(3.5)
4
>>> round(4.5)
4

我不明白这一点。 3.5四舍五入4但舍入4.5的方式不是5?是否有任何方法可以获得正常的舍入方式,如果5列(tenths)中的数字为>0.5或更高,它将会舍入到下一个整数?

编辑:在Python 2.7中,round函数表现正常。

回答 - 信用:Ignacio Vazquez-Abrams

保留Python 2舍入:

import math
>>> def old_round(n):
        return math.floor(n + 0.5)

>>> old_round(4.5)
5

0 个答案:

没有答案