JavaScript Runtime5h estimated

Numbers & Floating Point

Difficulty
Importance

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

Used in

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

Mastery checklist