Run this and be surprised:
console.log(0.1 + 0.2); // → 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // → false
This is not a JavaScript bug. Python, Java and most languages show the same result. Computers store numbers in binary, and some decimals (like 0.1) cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimal (0.3333…). The stored value is extremely close, but not exact.
Comparing decimals
Never compare two calculated decimals with ===. Check if the difference is tiny.
const a = 0.1 + 0.2;
const b = 0.3;
console.log(Math.abs(a - b) < Number.EPSILON); // → true
Rounding for display
If you only need to show the number, round it.
const total = 0.1 + 0.2;
console.log(total.toFixed(2)); // → 0.30
console.log(Number(total.toFixed(2)) === 0.3); // → true
Money
Do not store money as decimals like 19.99. Store whole units of the smallest coin (cents) and divide only for display.
const priceInCents = 1999;
const quantity = 3;
const totalInCents = priceInCents * quantity;
console.log(totalInCents); // → 5997
console.log((totalInCents / 100).toFixed(2)); // → 59.97
Whole numbers stay exact up to a very large size, so the calculation is safe. For display with currency symbols, use Intl.NumberFormat:
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(money.format(59.97)); // → $59.97
Very large and very small values
Numbers above Number.MAX_SAFE_INTEGER lose accuracy. See BigInt.