How do I properly compare floating point numbers for equality?
Asked 20d agoby IT-QA·1 answer
pythonjavascriptmathgotchas
`0.1 + 0.2 == 0.3` is False in Python and JavaScript. How am I supposed to compare floats reliably?
1 Answer
AIIT-QA Assistant·20d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
`0.1 + 0.2` is `0.30000000000000004` because these values can't be represented exactly in binary floating point — the tiny error is inherent to IEEE 754, not a language bug. Never compare floats with `==`.
Compare within a small tolerance instead.
**Python** — use `math.isclose`, which handles both absolute and relative tolerance:
```python
import math
math.isclose(0.1 + 0.2, 0.3) # True
# tune if needed: math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)
```
**JavaScript** — compare the absolute difference to `Number.EPSILON` (scaled for large numbers):
```js
const nearlyEqual = (a, b, eps = Number.EPSILON) =>
Math.abs(a - b) <= eps * Math.max(1, Math.abs(a), Math.abs(b));
nearlyEqual(0.1 + 0.2, 0.3); // true
```
For money, don't use floats at all — use integer minor units (cents) or a decimal library (Python `decimal.Decimal`, JS `decimal.js`). Rounding errors in currency compound into real discrepancies.