BugHunt

0.1 + 0.2 is 0.30000000000000004

JavaScript numbers are binary floating point, and 0.1 cannot be stored exactly. The tiny error shows up when you add, compare or print.

JavaScriptType errors

What it means

Every number in JavaScript is a 64-bit float. Just as 1/3 has no exact decimal form, 0.1 has no exact binary form, so it is stored as the nearest value. Adding two approximations gives 0.30000000000000004, and 0.1 + 0.2 === 0.3 is false. This is not a JavaScript bug: Python, Java and C behave the same way.

Common causes

1. Comparing floats with ===

Exact equality fails by the smallest possible amount.

Breaks

if (0.1 + 0.2 === 0.3) { ... }

Works

if (Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON) { ... }

2. Money stored as decimal amounts

Rounding errors accumulate across a cart or ledger.

Breaks

const total = 0.1 + 0.2;   // 0.30000000000000004

Works

const totalCents = 10 + 20;   // work in whole cents
const total = totalCents / 100;

3. Printing a raw float

Display needs formatting, not a different number.

Breaks

label.textContent = price * qty;

Works

label.textContent = (price * qty).toFixed(2);

How to find it in your own code

Decide what you need: for display, format with toFixed(2) or Intl.NumberFormat; for comparisons, allow a tolerance; for money, keep whole cents as integers and divide only for display.

Try it: fix this bug

medium

addPrices(0.1, 0.2) returns 0.30000000000000004 instead of 0.3.

function addPrices(a, b) {
    return a + b;
}
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors