Hiprup

What does 0.1 + 0.2 === 0.3 evaluate to and why?

It evaluates to false. 0.1 + 0.2 actually produces 0.30000000000000004.

  • Why — numbers use IEEE 754 floating-point (binary). Values like 0.1 and 0.2 can't be stored exactly, so tiny rounding errors build up.

  • Not a JS bug — this affects nearly every language that uses floating-point.

Fix: compare with a small tolerance, e.g. Math.abs(a - b) < Number.EPSILON, or work in integers (cents instead of dollars).

console.log(0.1 + 0.2);         // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false!

// Fix 1: Epsilon comparison
function areEqual(a, b) {
  return Math.abs(a - b) < Number.EPSILON;
}
console.log(areEqual(0.1 + 0.2, 0.3)); // true

// Fix 2: Integer arithmetic (financial)
function addCents(a, b) {
  return (Math.round(a * 100) + Math.round(b * 100)) / 100;
}
console.log(addCents(0.1, 0.2)); // 0.3

// Fix 3: toFixed (display only, returns string)
console.log((0.1 + 0.2).toFixed(1)); // '0.3'
console.log(+(0.1 + 0.2).toFixed(10)); // 0.3 (number)

IEEE 754 cannot represent 0.1 exactly in binary. The rounding error produces 0.30000000000000004.

Number.EPSILON (2.2e-16) is the smallest difference between representable numbers — comparing within this tolerance handles floating-point errors. Integer arithmetic (cents) avoids the issue entirely.

This is one of the most classic JS interview questions. Know WHY (IEEE 754 binary representation).

Show the three fixes: EPSILON comparison (general), integer math (financial), and toFixed (display). The cents approach for money is the most practical.

What does 0.1 + 0.2 === 0.3 evaluate to and why? | Hiprup