在 Python 2.x 中,内置的 round
具有以下行为:
if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0)
在 Python 3.x 中,this has changed更常见的:
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).
有没有一种简单的方法可以在 Python 2.x 中实现这种行为?不幸的是,future_builtins
模块不包括这个。也许我还没有找到另一个类似的模块?或者,另一种将 Python 3.x 函数拉入 Python 2.x 的方法?
显然,我可以编写一个产生所需行为的新函数,但我更好奇是否存在使用实际 Python 3.x 函数的解决方案,以避免增加不必要的复杂性和需要维护的代码。
最佳答案
除非你介意 numpy 依赖,numpy.around
可以做的事情:
>>> from numpy import around
>>> around(0.5)
0
>>> around(-0.5)
-0
>>> around(1.5)
2.0
关于Python 2 中的 Python 3 舍入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839140/