Why 0.1 + 0.2 Does Not Equal 0.3 in Most Programming Languages
Most programming languages return 0.30000000000000004 for 0.1 + 0.2 because they use IEEE 754 binary floating-point, which cannot store decimals like 0.1 exactly. The stored values are slightly off, and these tiny errors can accumulate, producing wrong results in calculations such as currency totals. For example, multiplying 4.35 by 100 yields 434.99999999999994, so truncating it to an integer loses a cent. The article recommends comparing floats with tolerance (such as math.isclose), storing money as integer cents, and building Decimal values from strings. It also notes that Python 3.12 and later use compensated summation in sum() to reduce rounding errors.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in