Why 0.1 + 0.2 is not 0.3

The IEEE 754 standard writes a number as a sign, an exponent and a mantissa, in base two: value = (−1)^sign × 1.mantissa × 2^(exponent − bias). Single precision has 8 exponent bits and 23 mantissa bits, double 11 and 52. It is the format of almost every processor and every programming language.

In base two only fractions whose denominator is a power of 2 have a finite form. 0.5 and 0.25 do, 0.1 does not: in binary it is 0.000110011001100… repeating, and it has to be cut. The stored value is the nearest one available, which for a float is 0.100000001490116…, and adding values that are already approximate makes the errors pile up.

That is why floating-point decimals are not compared with == but by checking that the difference is small, and money is counted in whole cents or with decimal types. Special values complete the format: signed zero, infinities, NaN and the subnormals that fill the gap near zero.

Common mistakes

  • Comparing two floats with ==: 0.1 + 0.2 == 0.3 is false in almost every language.
  • Using floats for money: the roundings add up. Whole cents or a decimal type are better.
  • Thinking a 32-bit float has 32 bits of precision: the mantissa has 24, about 7 decimal digits; a double has about 16.

Frequently asked questions

How many decimal digits do a float and a double have?

A 32-bit float guarantees about 7 significant decimal digits, a 64-bit double about 15 to 16. Beyond that, the digits you see reflect the binary approximation.

What are subnormal numbers?

Values smaller than the smallest normal one: the exponent is all zeros and the mantissa loses its implicit leading 1. They let numbers approach zero gradually, at the cost of precision.

Why are there +0 and −0?

Because the sign is a separate bit. The two zeros compare equal, but 1/+0 is +∞ and 1/−0 is −∞: they keep the side from which zero was reached.

How this calculation works

Value = (−1)^s × 1.f × 2^(e − bias) for normal numbers, with bias 127 in single and 1023 in double precision; for subnormals (e = 0) the value is (−1)^s × 0.f × 2^(1 − bias). An all-ones exponent with a zero mantissa is ±∞, with a non-zero mantissa NaN. The exact value is computed in decimal without rounding: every float is m × 2^k, and for negative k that equals m × 5^(−k) ÷ 10^(−k).