我正在使用python 3.8.5
总结一个浮点数,如下所示:
>> prices = [12.3, 11.99, 1.99, 5]
>> sum(prices)
31.279999999999998
如您所见,求和函数将返回舍入结果,其中实际和等于31.28
。什么总和具有相同的行为?
答案 0 :(得分:0)
这是由float
的实现而不是sum
引起的。您可以使用decimal.Decimal
来避免该问题。
import decimal
prices = [decimal.Decimal("12.3"), decimal.Decimal("11.99"), decimal.Decimal("1.99"), decimal.Decimal("5")]
print(sum(prices))
输出:
31.28