mathspythonjavascript
Computers can't add 0.1 and 0.2 (exactly)
Ask Python to add 0.1 and 0.2:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
▶ Try itYou get 0.30000000000000004, and False! JavaScript does exactly the same:
console.log(0.1 + 0.2);
▶ Try itWhy? Computers store numbers in binary (only 0s and 1s). Some numbers that look simple to us can't be written exactly in binary, just like 1/3 can't be written exactly in our decimal system: 0.333333... goes on forever.
0.1 in binary is 0.0001100110011001100... forever, so the computer keeps a very, very close approximation. Add two approximations and the tiny errors show up.
What do programmers do about it?
- Round when displaying:
round(0.1 + 0.2, 2)gives0.3. - Compare "close enough" instead of "exactly equal".
- For money, count in cents with whole numbers:
10 + 20 == 30is always exact.
import math
print(round(0.1 + 0.2, 2))
print(math.isclose(0.1 + 0.2, 0.3))
▶ Try it