我在使用Decimal数据类型时偶然发现了quantize方法的一个问题,它似乎给出了舍入错误:
Decimal('1.0055').quantize(Decimal('0.000')) # Should output 1.006
>> Decimal('1.006') # CORRECT output
Decimal('1.0045').quantize(Decimal('0.000')) # Should output 1.005
>> Decimal('1.004') # INCORRECT output
为什么有时是向上舍入,有时是向下舍入?你知道吗
默认舍入模式为
这正是你所看到的:
4
和5
之间,以及5
和6
之间的关系,分别是偶数(4
和6
)。你知道吗如果需要不同的舍入模式,则需要显式指定它。你知道吗
选择包括:
文档:https://docs.python.org/2/library/decimal.html#decimal.Context
请参见
rounding
参数到quantize()
:https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize相关问题 更多 >
编程相关推荐