gotchaMajorpending
Floating point comparison — never use == for floats
Viewed 0 times
floating point0.1 + 0.2epsilonBigDecimalDecimalcurrencyIEEE 754
nodejspythonbrowser
Error Messages
Problem
Arithmetic with decimal numbers gives wrong results: 0.1 + 0.2 !== 0.3. Price calculations are off by fractions of a cent. Equality comparisons fail on values that should be equal.
Solution
(1) For currency: use integers (cents) or Decimal types. Never float for money. JavaScript: use BigInt or libraries (dinero.js, currency.js). Python: from decimal import Decimal. Java: BigDecimal. (2) For comparison: use epsilon tolerance: Math.abs(a - b) < Number.EPSILON (for values near 1.0). For larger values, use relative epsilon. (3) For display: always round at the display layer, not during calculation. (4) For accumulation (summing many values): use Kahan summation to reduce error buildup. (5) Know the limits: float64 has ~15-17 significant decimal digits. Beyond that, precision is lost.
Why
IEEE 754 floating point represents numbers in binary. 0.1 in binary is a repeating fraction (like 1/3 in decimal), so it's stored with a tiny rounding error. These errors accumulate across operations.
Revisions (0)
No revisions yet.