Sub topic 9
Converting and rounding numbers
This chapter assumes you can run Python code, use print(), and tell int from float. It covers converting between numeric types, the different ways to drop a fractional part, and bool as a number.
Converting between numeric types
int(), float() and bool() each build a new object of that type from a value. They don't change the original.
print(float(3))
print(int(3.9))
print(int(-3.9))
print(bool(0), bool(0.0), bool(2.5))This prints 3.0, 3, -3, then False False True. Two points matter here:
int()truncates toward zero. It does not round, soint(-3.9)is-3, not-4.bool()isFalseonly for zero values (and for empty containers). Every other number isTrue.
Rounding with round()
round() rounds to the nearest value. A tie, where the value is exactly halfway between two integers, goes to the nearest even integer. This is called banker's rounding.
print(round(2.5))
print(round(3.5))
print(round(3.14159, 2))
print(type(round(3.7)), type(round(3.7, 1)))This prints 2, 4, 3.14, then <class 'int'> <class 'float'>. With one argument, round() returns an int. With a second argument, the number of digits, it returns the same type you gave it.
Choosing a rounding direction
When you need a specific direction, use the math module.
| Expression | Result for `3.7` | Result for `-3.7` |
|---|---|---|
| `int(x)` | 3 | -3 |
| `round(x)` | 4 | -4 |
| `math.floor(x)` | 3 | -4 |
| `math.ceil(x)` | 4 | -3 |
floor always moves toward negative infinity and ceil toward positive infinity. int is the same as floor only for positive numbers.
import math
x = -3.7
print(int(x), round(x), math.floor(x), math.ceil(x))This prints -3 -4 -4 -3.
bool is a number
bool is a subclass of int. True equals 1 and False equals 0, and both work in arithmetic.
print(True + True)
print(sum([True, False, True, True]))
print(int(True), float(False))
print(isinstance(True, int))This prints 2, 3, 1 0.0, then True. Adding up booleans counts how many are True, which is a common idiom: sum(n > 0 for n in values) counts the positive numbers.
Common mistakes
- Using
int()to round. It truncates, soint(2.9)is2. - Expecting
round(2.5)to be3. The result is2because of ties-to-even. - Treating the result of
round(x)as a float. It is anint. - Rounding a float for display and then reusing it in calculations. Round only when you present or store the final value. For display, an f-string format such as
f"{x:.2f}"avoids altering the number.
Exercise
Without running it, what does this print? import math; v = -2.5; print(int(v), round(v), math.floor(v), math.ceil(v))
Show answer
It prints -2 -2 -3 -2. int truncates toward zero to -2. round(-2.5) is a tie, so it goes to the even integer -2. floor moves down to -3. ceil moves up to -2.
Exercise
A list flags = [True, False, True] is given. Which expression gives the number of True values, and what type is the result?
Show answer
sum(flags) gives 2, and the type is int, because bool is a subclass of int.