Python rounding error with simple sum
问题 >>> sum([0.3, 0.1, 0.2]) 0.6000000000000001 >>> sum([0.3, 0.1, 0.2]) == 0.6 False What can I do to make the result be exactly 0.6? I don't want to round the result to a certain number of decimal digits because then I could lose precision for other list instances. 回答1: A float is inherently imprecise in pretty much every language because it cannot be represented precisely in binary. If you need exact precision use the Decimal class : from decimal import Decimal num1 = Decimal("0.3") num2 =