Why does 0.1 + 0.2 == 0.3 return False in Python, and how do you compare floats correctly?
Floats are stored in binary, and 0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004. Compare floats with math.isclose(), or use decimal.Decimal when exact decimal arithmetic is needed, such as for money.
Explain it simply
Try writing 1/3 as a decimal: 0.3333... you have to stop somewhere, so it is slightly off. Computers store floats in binary (base 2), and in binary even 0.1 is a never-ending fraction. Python stores the nearest value it can fit in 64 bits, so tiny errors creep in and become visible when you add numbers.
This is not a Python bug. Java, JavaScript and C behave the same way because they all use the IEEE 754 standard.
Example
import math
from decimal import Decimal
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
# For money, build Decimals from strings, not floats
price = Decimal("0.10") + Decimal("0.20")
print(price) # 0.30
print(price == Decimal("0.30")) # Truemath.isclose uses a relative tolerance of 1e-09 by default; pass abs_tol when comparing values near zero.
What to say in the interview
"Floats are binary approximations, so 0.1 + 0.2 is not exactly 0.3. I never compare floats with ==; I use math.isclose. For currency, like a UPI payment total in rupees, I use Decimal created from strings, or store amounts as integer paise."
Common mistakes
- Writing
Decimal(0.1): this copies the float's error. UseDecimal("0.1"). - Using
round()as a comparison fix; it hides the issue rather than solving it.