Why is 0.1 + 0.2 not equal to 0.3 in JavaScript?
Numbers are stored in binary floating point (IEEE 754), and 0.1 and 0.2 cannot be represented exactly in binary, so the sum is 0.30000000000000004. Compare with a small tolerance, or do money maths in whole paise.
Explain it simply
Try writing 1/3 as a decimal: 0.3333... it never ends, so you have to cut it off somewhere. Computers store numbers in binary, and in binary the number 0.1 is like 1/3 in decimal: it goes on forever. JavaScript stores a rounded version. When you add two rounded numbers, the tiny errors show up.
This is not a JavaScript bug. Python, Java and C give the same result for the same floating-point types, because they all follow the IEEE 754 standard.
Example
console.log(0.1 + 0.2); // Output: 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // Output: false
// Fix 1: compare with a tolerance
const close = Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON;
console.log(close); // Output: true
// Fix 2: round for display (returns a string)
console.log((0.1 + 0.2).toFixed(2)); // Output: 0.30
// Fix 3: for money, work in paise (integers)
const totalPaise = 1050 + 2099; // Rs 10.50 + Rs 20.99
console.log(totalPaise / 100); // Output: 31.49What to say in the interview
"JavaScript numbers are 64-bit IEEE 754 doubles. Decimal fractions like 0.1 have no exact binary form, so they're stored slightly off and the error appears after addition. To compare, I check that the difference is below Number.EPSILON or a tolerance that fits the problem. For money, I store integer paise or use a decimal library, and only format to rupees at display time."
Common mistakes
- Using
toFixedand then doing more maths on the result, forgetting it returns a string. - Storing prices as floats in a payment system.