Why 0.1 + 0.2 isn't 0.3
Some decimal numbers can't be stored exactly. You'll see why, and learn to show tidy numbers, especially money.
1. A strange result
print(0.1 + 0.2)
0.30000000000000004
You'd expect 0.3. That's not a bug in Python. Almost every programming language does this.
2. Why it happens
Computers store numbers in binary, using only 0s and 1s. Some decimal numbers can't be written exactly in binary.
It's like writing one third as a decimal number: 0.3333, forever. You have to stop somewhere, so it's very slightly off. In binary, 0.1 has the same problem. The tiny errors add up, and you see them at the end.
3. Showing tidy numbers
Python has a tool called round. It rounds a number to as many decimal places as you ask for.
print(round(0.1 + 0.2, 2))
0.3
round( )Rounds a number.0.1 + 0.2The number.2How many decimal places. Two places gives 0.3.Press Run
4. One thing to watch: money
A rupee that's off by a tiny bit, across a million payments, becomes real money. So banks don't use plain floats for money. They count in whole paise, as whole numbers, and only turn it back into rupees to show it.
price_paise = 4950 print(price_paise / 100)
49.5
4950 paise is 49.5 rupees, and the maths stays exact until the very end. Python also has a special type called Decimal for exact money, which you'll meet later.
5. Where it's used
Anywhere money is calculated: bills, interest, salaries. Interviewers also love asking why 0.1 plus 0.2 isn't 0.3, and now you know.