Data Structures & Algorithms / Module 10: Correctness and reviewing AI code

Topic 10.3

Floating point

Why 0.1 + 0.2 isn't 0.3, and how to handle money and big IDs safely.

8 min · beginner

Watch: 0.1 added ten times should be 1, but the computer gets 0.9999999999999999. With whole numbers, it's exact.

0
  • moving now
  • being checked
Step 1 of 12

Add 0.1 ten times. The result should be 1.

Computers store decimals in binary, and most decimal fractions have no exact binary form.

Like 1/3 in decimal

Try writing 1/3 in decimal: 0.3333… and it never ends. With only 5 digits you write 0.33333, and 3 × 0.33333 = 0.99999, not 1. Computers hit the same thing with 0.1 in binary: 0.0001100110011… repeating forever. A 64-bit number keeps about 15 to 17 decimal digits, then rounds. That tiny error carries along every time you add.

What to do about it

  • Don't compare with ===. Check whether the difference is small enough.
  • Money as whole numbers: store $12.34 as 1234 cents. Divide by 100 only when displaying. Stripe and most payment gateways work this way.
  • In databases: use DECIMAL(12, 2) or NUMERIC for money, not FLOAT.
  • Round at the end, once, for display. Don't round at every step of a calculation.
  • Big integers: JavaScript is only exact up to 2^53 (about 9 × 10^15). 64-bit IDs from a database or Twitter must travel as strings or BigInt.
Code, for programmersComparing, and counting money
0.1 + 0.2 === 0.3;                                  // false
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON;         // true: close enough

// money: whole cents, divide only for display
const priceCents = 1999;                            // $19.99
const totalCents = priceCents * 3;                  // 5997, exact
const label = (totalCents / 100).toFixed(2);        // "59.97"

// big IDs
Number("9007199254740993");                         // 9007199254740992 (wrong!)
BigInt("9007199254740993");                         // 9007199254740993n

Quiz

  1. Why isn't 0.1 + 0.2 exactly 0.3?

  2. The best way to store a price of $15.50 in a database?

  3. An API sends id: 9007199254740993 as a JSON number. What's the risk in JavaScript?

0 of 3 answered.