Why 0.1 + 0.2 Does Not Equal 0.3
The classic floating-point puzzle explained. Learn why 0.1 + 0.2 produces 0.30000000000000004 in IEEE 754 and how to handle floating-point comparison correctly.
Decimal Value
0.30000000000000004
Float32 Hex
0x3E99999A
Float64 Hex
0x3FD3333333333334
Detailed Explanation
The expression 0.1 + 0.2 !== 0.3 is the most famous floating-point surprise. It occurs in virtually every programming language because 0.1, 0.2, and 0.3 cannot be represented exactly in binary floating-point.
Why 0.1 is not exact in binary:
The decimal number 0.1 in binary is 0.0001100110011... — an infinitely repeating pattern, similar to how 1/3 = 0.333... in decimal. IEEE 754 must round this to the nearest representable value.
The closest float64 to 0.1 is:
0.1000000000000000055511151231257827021181583404541015625
The closest float64 to 0.2 is:
0.200000000000000011102230246251565404236316680908203125
The addition:
When the stored values are added:
0.10000000000000000555... + 0.20000000000000001110... = 0.30000000000000004440...
The nearest representable float64 to this result is:
0.3000000000000000444089209850062616169452667236328125
But the nearest representable float64 to 0.3 is:
0.299999999999999988897769753748434595763683319091796875
These are different values, so 0.1 + 0.2 !== 0.3.
The bit-level view:
| Value | Float64 Hex |
|---|---|
| 0.1 | 0x3FB999999999999A |
| 0.2 | 0x3FC999999999999A |
| 0.1+0.2 | 0x3FD3333333333334 |
| 0.3 | 0x3FD3333333333333 |
Notice that 0.1+0.2 and 0.3 differ in the last hex digit: 4 vs. 3.
How to compare floats correctly:
- Epsilon comparison:
Math.abs(a - b) < Number.EPSILONfor values near 1.0 - Relative epsilon:
Math.abs(a - b) < Math.max(Math.abs(a), Math.abs(b)) * tolerance - Fixed-point: multiply by 100 for currency (work in cents, not dollars)
- Decimal libraries: use
decimal.jsorBigDecimalfor exact decimal arithmetic
This is not a bug:
This behavior is correct according to IEEE 754. It is inherent to representing base-10 fractions in base-2. The same issue exists in C, C++, Java, Python, Rust, Go, and every other language that uses IEEE 754 floating-point.
Use Case
Every developer needs to understand this behavior to write correct numerical comparisons, implement financial calculations without rounding errors, and explain floating-point precision issues to teammates and stakeholders.