Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.3

Comparing 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
true

Money 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.1

Common 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.9999999999999999

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.