How a float is stored
An IEEE-754 number packs three fields into its bits: a sign (1 bit), a biased exponent, and a mantissa (the fraction). The value is roughly sign × 1.mantissa × 2^(exponent − bias). float32 gives the exponent 8 bits and the mantissa 23; float64 gives 11 and 52, which is why doubles carry about 15–16 significant decimal digits to a float's 7.
| Sign | Exponent | Mantissa | Bias | |
|---|---|---|---|---|
| float32 | 1 | 8 | 23 | 127 |
| float64 | 1 | 11 | 52 | 1023 |
Why 0.1 + 0.2 ≠ 0.3
0.1 has no exact binary representation — like 1/3 in decimal, it repeats
forever. The nearest float64 to 0.1 is actually
0.1000000000000000055511151231257827021181583404541015625. Type
0.1 above and the "rounding error" line shows this gap. Add two
such approximations and the small errors don't cancel, so the sum is a hair
off 0.3. This is why you compare floats with a tolerance, and use decimal or
integer types for money.
The special values
- ±0 — zero has a sign bit; +0 and −0 compare equal but differ in bits (and in 1/x, which gives ±∞).
- ±Infinity — exponent all ones, mantissa zero. Overflow and x/0 land here.
- NaN — exponent all ones, mantissa non-zero. The top mantissa bit distinguishes quiet from signaling NaN. Famously, NaN ≠ NaN.
- Subnormals — exponent all zeros; these fill the gap between the smallest normal number and zero, at reduced precision.
Frequently asked questions
- What's the hex for a given float?
- Type the decimal and read the Hex field — that's the raw bit pattern as you'd see it in a memory dump or a debugger. Type hex to go the other way.
- Why does my float32 show a longer decimal than I typed?
- The "stored value" is the exact value those bits represent, which is rarely the round number you typed — it's the nearest representable float. The difference is the rounding error.
- What is a ULP?
- The "unit in the last place" — the gap between one representable float and the next. It grows as the numbers get larger, which is why float precision is relative, not absolute.
- Need plain integer base conversion instead?
- Use the number base converter or the programmer's calculator for integer hex/binary work.