Floating-Point Precision in JavaScript
The infamous 0.1 + 0.2 !== 0.3 surprise is not a JavaScript bug — it is a fundamental property of IEEE 754 double-precision binary floating-point arithmetic, shared by virtually every mainstream programming language. Understanding the cause helps you choose the right solution.
Why Precision is Lost
Decimal fractions like 0.1 cannot be represented exactly in binary floating point, just as 1/3 cannot be represented exactly in decimal. The stored approximation introduces tiny errors that accumulate with arithmetic.
Solutions
- Round for display: use
toFixed()ortoPrecision()when presenting values to users. - Integer arithmetic: multiply by a power of ten (e.g., work in cents rather than dollars), perform integer arithmetic, then divide.
- Epsilon comparison: compare floats with a tolerance using
Number.EPSILON. - Decimal libraries: for financial applications use a library like
decimal.jsthat tracks precision explicitly.