Codiqo

Learn Python · lesson 10 of 60 · about 7 minutes

Number Tools and Float Surprises

Stop the assistant showing a negative amount with max(), round money properly, and see why 0.1 + 0.2 isn't quite 0.3.

What you'll learn

  • Round numbers with round()
  • Use abs(), min() and max()
  • Understand float precision

Saved too much?

If Sam has saved 150 for a 120 bike, the assistant says Still to save: -30.00. Python has built-in tools for jobs like this:

  • max(a, b) gives the bigger value, and min(a, b) the smaller
  • abs(x) drops the minus sign: abs(-30) is 30
  • round(x) rounds to a whole number, and round(x, 2) to two decimal places

So max(0, price - saved) never goes below 0.

Tools that work on numbers

print(max(0, 120 - 150))
print(min(3, 8, 5))
print(abs(-30))
print(round(4.6))
print(round(3.14159, 2))

Output

0
3
30
5
3.14

Why 0.1 + 0.2 looks odd

Computers store decimals in binary, and most decimals, like 0.1, can't be stored exactly, only very closely. Usually you never notice, but now and then the tiny difference shows.

A float surprise

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2))

Output

0.30000000000000004
False
0.3

Rounding halves

round() sends an exact half to the nearest even number: round(2.5) is 2 and round(3.5) is 4. That's on purpose: it stops halves always pushing totals up. For money, round to two places, or show it with :.2f.

Tip

round() needs a number. An answer straight from input() is text, so convert it with float() before you round it.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.