python - Decimal.quantize 舍入误差

标签 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

为什么有时向上舍入,有时向下舍入?

最佳答案

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

默认舍入模式为

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

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

关于python - Decimal.quantize 舍入误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705777/

相关文章:

javascript - 四舍五入小数javascript

python - 如何在python中将以0开头的十六进制字符串转换为一定长度的字节

python - 从大型 MongoDB 读取,写入 JSON

c# - Xamarin.Forms:Android <Entry> 和依赖服务?

powershell - 如何在 PowerShell 中将诸如 5.7303333333e+02 之类的字符串转换为十进制?

c - 在 C 中使用舍入和千位分隔符格式化字符串的最有效方法是什么?

python - 如何查看 TensorFlow session 的默认配置选项?

python - python 中的动态语句在一个实体发生变化时绘制图形

gcc - 如何在 GCC 中打印/转换十进制浮点值?

java - 四舍五入到 2 位小数并通过 TextView