我在使用 round() 时注意到一个奇怪的行为具有负舍入因子(参数 ndigits)和 decimal 的函数模块。
我正在使用 Python 3(特别是 3.6.3,但我不知道特定的次要版本是否对这种情况很重要)。
使用 float 它看起来很正常:
>>> round(10000 / 3, 2)
3333.33
>>> round(10000 / 3, 1)
3333.3
>>> round(10000 / 3, 0)
3333.0
>>> round(10000 / 3, -1)
3330.0
>>> round(10000 / 3, -2)
3300.0
使用 Decimal 结果是正确的,但是当使用负舍入因子时它会变成科学记数法:
>>> from decimal import Decimal
>>> round(Decimal('10000') / 3, 2)
Decimal('3333.33')
>>> round(Decimal('10000') / 3, 1)
Decimal('3333.3')
>>> round(Decimal('10000') / 3, 0)
Decimal('3333')
>>> round(Decimal('10000') / 3, -1)
Decimal('3.33E+3')
>>> round(Decimal('10000') / 3, -2)
Decimal('3.3E+3')
我的快速修复是将 0 添加到结果中,这会将符号恢复为“正常”(非科学):
>>> round(Decimal('10000') / 3, -1) + 0
Decimal('3330')
>>> round(Decimal('10000') / 3, -2) + 0
Decimal('3300')
我不认为这被归类为错误,因为只有符号而不是实际值受到影响,但这对我来说还是很奇怪。
有谁知道我为什么会看到这种行为?您知道这是故意的还是小错误?
请您参考如下方法:
这是正常的并且是有意的。 Decimal 跟踪有效数字,而 Decimal repr 旨在保留有效数字。 Decimal('3.3E+3') 有两位有效数字,而 Decimal('3300') 有四位。
