【问题标题】:Why is Python: 3.8 rounding Decimal 1120.50 down instead of up? [duplicate]为什么 Python: 3.8 四舍五入 Decimal 1120.50 向下而不是向上? [复制]
【发布时间】: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


【解决方案1】:

round 内置函数在两个值之间向偶数解舍入。

此基础轮函数定义记录在此:https://docs.python.org/3.7/library/functions.html#round

由于decimal包是内置的,而不是基本类型,它实现了自己的__round__函数,该函数遵循两个值之间舍入到偶数解的内置标准。

这没有很好的记录,但我在代码本身中验证了:https://github.com/python/cpython/blob/1f0cde678406749524d11e852a16bf243cef5c5f/Lib/_pydecimal.py#L1890

没有办法覆盖round 函数对decimal 对象的工作方式。

改用量化

decimal 包提供了一个函数quantize,它允许您进行舍入和设置舍入类型。

量化记录在这里:https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize

圆形类型在这里:https://docs.python.org/3/library/decimal.html#rounding-modes

【讨论】:

  • 我也阅读了文档,但不知何故错过了四舍五入到最接近偶数的细节。对不起。谢谢回复。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2014-08-26
相关资源
最近更新 更多