Numbers & Floating Point
The problem
JavaScript represents all numbers — integers and decimals alike — using one format, and that format cannot represent most decimal fractions exactly, producing surprising results (0.1 + 0.2 !== 0.3) unless you understand why the representation itself is approximate.
Why now
Number systems and bases already explained binary representation; floating-point is the specific binary encoding scheme (a sign, an exponent, and a fraction) used for non-integer numbers, and its rounding behavior is a direct, provable consequence of that binary encoding rather than a language bug.
Mental model
Just as 1/3 has no exact finite decimal representation, most decimal fractions (like 0.1) have no exact finite binary representation — floating-point stores the closest approximation it can in a fixed number of bits. Every 'floating-point weirdness' bug is this single fact resurfacing: the number you typed and the number actually stored are subtly different.
Requires
- Number Systems & BasesMathematical Thinking
Floating-point is a binary positional representation with a twist (an exponent for scale); you need binary place-value understanding already in place before the specific 'why can't 0.1 be exact' explanation makes sense.
Used in
- The infamous 0.1 + 0.2 !== 0.3 result, and why it's not a JavaScript-specific bug
- Financial calculations, which require special handling (integer cents, decimal libraries) to avoid floating-point rounding errors
- Number.EPSILON-based comparisons instead of direct equality for floating-point values
- BigInt, JavaScript's separate type for exact arbitrary-precision integers
Projects
- Run 0.1 + 0.2 in a console, observe the result, and explain the discrepancy in terms of binary floating-point representation
- Write a safe floating-point comparison function using an epsilon tolerance instead of strict equality
Examples
- 0.1 + 0.2 === 0.30000000000000004 in JavaScript, because neither 0.1 nor 0.2 has an exact binary representation
- Storing currency as integer cents instead of decimal dollars avoids floating-point rounding errors entirely
Resources
- 0.30000000000000004.comarticle
- MDN — Numberdocs
Mastery checklist
- I can explain why 0.1 + 0.2 !== 0.3 in terms of binary floating-point representation
- I can write a safe floating-point equality check using an epsilon tolerance
- I can explain why financial calculations avoid raw floating-point arithmetic
- I can explain when BigInt is appropriate instead of Number