SyntaxStudy
Sign Up
JavaScript Floating-Point Precision and Solutions
JavaScript Intermediate 8 min read

Floating-Point Precision and Solutions

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() or toPrecision() 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.js that tracks precision explicitly.
Example
console.log(0.1 + 0.2);          // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);  // false
function approxEqual(a, b, eps) {
  eps = eps || Number.EPSILON;
  return Math.abs(a - b) < eps;
}
console.log(approxEqual(0.1 + 0.2, 0.3)); // true
const price1 = 0.10;
const price2 = 0.20;
const totalCents = Math.round(price1 * 100) + Math.round(price2 * 100);
console.log(totalCents / 100);    // 0.3  (exact)
console.log((1.005).toFixed(2));  // '1.00' — beware!
Pro Tip

For any application that handles money, always work in the smallest currency unit (cents, pence, etc.) using integer arithmetic, then convert to the display unit only at the presentation layer.