IEEE 754 Floating Point Converter · Tutorial

How to see why 0.1 isn't stored exactly in floating point

6 min readintermediateUpdated

Your code prints 0.30000000000000004 when adding 0.1 and 0.2, or a money total is off by a fraction of a cent. This tutorial looks at the bits behind 0.1 in 32-bit and 64-bit precision, shows the exact stored value, and explains how to avoid problems in your code.

What you need

Steps

  1. Enter 0.1 as a 32-bit float

    Type 0.1 and choose 32-bit float (single). The hex pattern is 3DCCCCCD. In the bit strip you can see the repeating 1100 in the mantissa, the binary version of a repeating decimal.

  2. Read the stored value

    The exact stored value is 0.100000001490116119384765625. The rounding error is about -1.49e-9, meaning the stored value is slightly larger than 0.1.

  3. Switch to 64-bit

    Choose 64-bit double, the type JavaScript and Python use. The pattern is 3FB999999999999A and the error shrinks to about -5.55e-18, but it isn't zero.

  4. Try a value that is exact

    Type 0.5 or 0.375. These are sums of powers of two (1/2, and 1/4 + 1/8), so the error is shown as none. Only such values are stored exactly.

  5. Fix it in code

    Compare floats with a small tolerance instead of ===, round only when displaying, and store money in whole cents (integers) or use a decimal type.

Try it yourself

Opens the IEEE 754 Floating Point Converter with this tutorial's sample loaded.

Try it now

Common mistakes

Blaming the language
Every language using IEEE 754 doubles behaves the same way. It's a property of binary fractions, not a bug.
Rounding too early
Rounding after every step can add up errors. Keep full precision and round once at the end.
Using floats for currency
Amounts like 19.99 can't be stored exactly. Use integers in the smallest unit or a decimal library.

Next steps

Go back to the IEEE 754 Floating Point Converter, or keep going with one of these: