Why 0.1 + 0.2 is not 0.3 and what to do about it
Short answer
Fractions are stored in binary form, and some of them, like 0.1, cannot be written exactly. Round the result for display:
console.log(0.1 + 0.2);
console.log(Number((0.1 + 0.2).toFixed(2)));Output:
0.30000000000000004
0.3Comparing fractions
Do not compare fractions with ===. Check that the difference is tiny:
const equal = (a, b) => Math.abs(a - b) < Number.EPSILON;
console.log(0.1 + 0.2 === 0.3);
console.log(equal(0.1 + 0.2, 0.3));Output:
false
trueMoney in cents
For money, count in whole cents and convert to dollars only at the end:
const prices = [19.99, 5.01, 0.1];
const totalCents = prices.reduce((sum, price) => sum + Math.round(price * 100), 0);
console.log(totalCents / 100);Output:
25.1Common mistake
The error accumulates when you add many fractions in a loop:
let sum = 0;
for (let i = 0; i < 10; i++) sum += 0.1;
console.log(sum);Output:
0.9999999999999999Functions used in this recipe
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- Math.round — Rounds a number to the nearest integer.
- Number.EPSILON — The smallest difference between 1 and the next number — for comparing fractions.