← Intro to programming with Python
Whole numbers, decimals and rounding
Know int from float, and round numbers for display.
Python has two kinds of numbers. An int is a whole number like 7. A float is a number with a decimal point like 7.5. Floats are stored in binary inside the computer, so a few decimals cannot be stored exactly, and you may see 0.1 + 0.2 come out as 0.30000000000000004. That is not a bug in your program, it is how every computer works, and the fix for display is round(number, 2), which keeps two decimal places.
print(0.1 + 0.2) # 0.30000000000000004
print(round(0.1 + 0.2, 2)) # 0.3
print(round(7.9)) # 8
print(int(7.9)) # 7 (chops, does not round)
print(type(7), type(7.9))round() goes to the nearest value. int() simply cuts off the decimals. type() tells you which kind of value you have.
Common mistake: using int() when you meant to round. int(9.99) is 9, not 10.
A surprise: round(2.5) gives 2 and round(3.5) gives 4. When a number is exactly halfway, Python rounds to the nearest EVEN number. For money you will mostly use round(x, 2), where this rarely matters.
Mixing an int and a float gives a float: 3 + 0.5 is 3.5.