🔢 Numbers & Math, lesson 4 of 5
Rounding and float surprises
round(), int(), abs(), min() and max(), and why 0.1 + 0.2 isn't exactly 0.3.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Some built-in functions help tidy up numbers:
round(x)rounds to the nearest whole numberround(x, 2)rounds to 2 decimal placesint(x)chops off the decimals (no rounding)abs(x)gives the distance from zeromin(...)/max(...)pick the smallest / largest
Example
Tidying numbers
Change price and the number of decimal places.
Quiz
What does this print?
3 3
4 4
3 4
3.99 4
Computers store floats in binary, so most decimals are tiny approximations. Usually you never notice, but sometimes it shows:
Example
The famous 0.1 + 0.2
The last line surprises many people: Python rounds exact halves to the nearest even number ("banker's rounding").
Exercise
Split the bill
The bill is 47.80 and you add a 15% tip. Compute the
grand total (bill + tip), rounded to 2 decimal
places, and store it in total.
Quiz
What does this print?
4
10
-10
7