【发布时间】:2021-06-14 09:39:03
【问题描述】:
我正在使用 python 3.8.5 和四舍五入的小数,而不是可能表现得很奇怪的浮点数。
Python 通常会四舍五入所有小数。0.50 向上舍入的小数会正确。
但是,只有 Decimal(1120.50) 向下舍入。我的代码中可能有什么错误。
重新创建
import decimal
round(decimal.Decimal(1119.50))
# OK: Expected output 1120, actual output 1120
round(decimal.Decimal(1120.50))
# Wrong: Expected output 1121, actual output 1120
round(decimal.Decimal(1121.50))
# OK: Expected output 1122, actual output 1122
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
默认将X.5四舍五入到最接近的偶数;这避免了如果您总是在中途情况下沿相同方向四舍五入会导致的偏差。如果它们更好地满足您的需求,您可以选择其他几种舍入模式,请参阅
decimal模块文档。 -
@jasonharper 实际上无法使用
round内置函数设置小数的舍入模式。它设置为 ROUND_HALF_EVEN
标签: python python-3.x