下面描述的问题发生在 Python3 和 Django 1.9.4
在我的 Django 项目中,为了计算 sale_amount 的折扣,我使用下面的代码行
discount = round((sale_amount - tax_amount ) * discount_rate,2)
上述变量取值如下
sale_amount,tax_amount, discount_rate = 30.00, 6.75, 0.02000000
从 Django 模型对象中获取的变量值都是相同的类型,即 decimal.Decimal
根据上述代码行在 Django 项目文件中计算出的折扣是 0.46
当我使用上述金额和公式计算折扣时,我在 Django 控制台中得到 value: 0.47
我无法弄清楚为什么 Django 控制台和项目计算之间存在 0.01 差异。
请您参考如下方法:
(30 - 6.75) * 0.02 的结果是 0.465。所以我们希望四舍五入时得到 0.47。但这里似乎有一个解释:round() documentation .
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
