Why 0.1 + 0.2 Is Not 0.3
Open almost any programming language and type 0.1 + 0.2. Python, JavaScript, Java and C all agree on the answer: 0.30000000000000004. It is not a bug in the language. It is what happens when you write decimal fractions with binary digits, and every programmer who works with measurements or money needs to understand it.
The rule
Binary fractions are sums of halves; 0.1 is not, so it is rounded.
After the binary point, the places are worth ½, ¼, ⅛, 1/16 and so on, each half of the one before:
binary 0.1 = 1/2 = decimal 0.5
binary 0.011 = 1/4 + 1/8 = decimal 0.375
decimal 0.1 = binary 0.0001100110011… (repeats forever)A number is exact in binary only if it can be built from a finite sum of these halves. In other words, written as a fraction in lowest terms, its denominator must be a power of two: ½, ¾, ⅝ and 3/16 are fine.
A tenth has denominator 10 = 2 × 5. That factor of 5 makes the binary pattern repeat forever, just as 1/3 = 0.3333… repeats forever in decimal. A computer keeps only a fixed number of bits, so it stores the nearest value it can. The stored "0.1" is a tiny bit more than 0.1, the stored "0.2" is too, and their sum lands just above the value stored for 0.3.
The error is tiny, around the 17th significant digit. It becomes a problem when you test for exact equality, or when millions of small errors pile up.
The shortcut
To know whether a decimal is stored exactly, write it as a fraction in lowest terms and look at the denominator. Only 2s in it: exact. Any other factor: rounded.
0.75
0.75 = 3/4. Denominator 4 = 2 × 2: exact.
The trap: thinking "short decimal" means "exact". 0.1 is short in decimal but infinite in binary.
Drills
Answer fast — trust the rule.
Which value is stored exactly as a binary floating-point number?
Why is 0.1 not stored exactly?
What does 0.1 + 0.2 == 0.3 give in Python?
Which is the best decimal analogy for 0.1 in binary?
Remember
- Binary fractions are sums of halves; 0.1 is not, so it is rounded.
- Lowest-terms denominator a power of two: exact. Anything else: rounded.
- The trap: a short decimal can be an endless binary fraction.
