Skip to content

JavaScript Tutorial Numbers and Math

JavaScript Floating Point Numbers

Lesson 36 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Run this and be surprised:

script.js
JS
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.

script.js
JS
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.

script.js
JS
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.

script.js
JS
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:

script.js
JS
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.

info
It is the same everywhere
Whenever you see “weird” decimal results in any language, floating point is the reason. Knowing this saves hours of confusion.