为什么 Python:3.8 将十进制 1120.50 向下舍入而不是向上舍入?

时间:2021-03-17 03:16:15

标签: python python-3.x

我使用的是 python 3.8.5 和四舍五入的小数,而不是可能表现奇怪的浮点数。

Python 通常会四舍五入所有小数。小数正确四舍五入,其中 .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

任何帮助将不胜感激。

谢谢

1 个答案:

答案 0 :(得分: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