十进制.量化舍入

2024-04-19 06:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用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

为什么有时是向上舍入,有时是向下舍入?你知道吗


Tags: 方法output错误数据类型decimalshouldcorrectincorrect
1条回答
网友
1楼 · 发布于 2024-04-19 06:41:41
<> >太长了,读不下去了,这就是所谓的{a1}。< /强>

默认舍入模式为

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

这正是你所看到的:45之间,以及56之间的关系,分别是偶数(46)。你知道吗

如果需要不同的舍入模式,则需要显式指定它。你知道吗

选择包括:

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)

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

请参见rounding参数到quantize()https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize

相关问题 更多 >