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
Enter 0.1 as a 32-bit float
Type
0.1and choose 32-bit float (single). The hex pattern is3DCCCCCD. In the bit strip you can see the repeating1100in the mantissa, the binary version of a repeating decimal.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.
Switch to 64-bit
Choose 64-bit double, the type JavaScript and Python use. The pattern is
3FB999999999999Aand the error shrinks to about -5.55e-18, but it isn't zero.Try a value that is exact
Type
0.5or0.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.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.
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: