本文介绍了如何在 Python 3.x 中舍入 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 2 中 舍入 远离 0
,例如,round(0.5)
是 1.0
.
然而,在 Python 3.x 中,舍入是朝着偶数选择完成的,所以 round(0.5)
是 0
.
我可以在 Python 3.x 中使用什么函数来获得旧行为?
In Python 2 rounding is done away from 0
, so, for example, round(0.5)
is 1.0
.
In Python 3.x, however, rounding is done toward the even choice, so round(0.5)
is 0
.
What function can I use in Python 3.x to get the old behavior?
推荐答案
如果您的代码对性能不是特别敏感,您可以使用标准的decimal
库来实现您想要的结果.Decimal().quantize()
允许选择舍入方法:
If your code is not particularly performance sensitive, you can use the standard decimal
library to achieve the result you want. Decimal().quantize()
allows choosing the rounding method:
from decimal import Decimal, ROUND_HALF_UP
result = float(Decimal(0.5).quantize(Decimal(0), rounding=ROUND_HALF_UP))
print(result) # Will output 1.0
这篇关于如何在 Python 3.x 中舍入 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!