Decimal.quantize舍入误差

时间:2018-06-05 17:26:47

标签: python decimal rounding truncate

在使用Decimal数据类型时,我偶然发现了量化方法的问题,它似乎给出了舍入错误:

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

为什么它有时会四舍五入,有时会四舍五入?

1 个答案:

答案 0 :(得分:2)

tl; dr这就是所谓的bankers' rounding

默认的舍入模式是

ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)

这正是您所看到的:45之间以及56之间的关系将转为偶数({分别为{1}}和4

如果您想要一个不同的舍入模式,您需要明确指定它。

选择是:

6

文档:https://docs.python.org/2/library/decimal.html#decimal.Context

请参阅ROUND_CEILING (towards Infinity), ROUND_DOWN (towards zero), ROUND_FLOOR (towards -Infinity), ROUND_HALF_DOWN (to nearest with ties going towards zero), ROUND_HALF_EVEN (to nearest with ties going to nearest even integer), ROUND_HALF_UP (to nearest with ties going away from zero), or ROUND_UP (away from zero). ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero) 的{​​{1}}参数:https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize