gpt4 book ai didi

python - 如何在 Python 3.x 中舍入 0?

转载 作者:太空狗 更新时间:2023-10-29 21:35:57 27 4
gpt4 key购买 nike

在 Python 2 中 rounding0 开始,因此,例如,round(0.5)1.0
然而,在 Python 3.x 中,rounding是朝着偶数选择的方向进行的,所以 round(0.5)0
我可以在 Python 3.x 中使用什么函数来获得旧行为?

最佳答案

如果您的代码对性能不是特别敏感,您可以使用标准的decimal 库来实现您想要的结果。 Decimal().quantize() 允许选择舍入方法:

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 - 如何在 Python 3.x 中舍入 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689594/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com