Sub topic 9
Converting and rounding numbers
This chapter covers how Python changes a number from one type to another, and how it rounds. Both are places where code runs without errors and still gives a wrong answer. You should already know int, float, Decimal, the arithmetic operators, and why 0.1 + 0.2 != 0.3.
Conversion creates a new object
Calling int(x), float(x) or Decimal(x) builds a new object of that type from x. It does not change x or the type of its name. The new object is a different value, and sometimes a different number than you expected.
Python also converts implicitly in mixed arithmetic. When an int meets a float, the int becomes a float and the result is a float. Decimal is the exception. It mixes with int, but adding it to a float raises TypeError, so Python never silently reintroduces binary rounding error.
from decimal import Decimal
print(type(1 + 2.0))
print(Decimal("1.10") + 2)
try:
Decimal("1.10") + 2.0
except TypeError as e:
print("TypeError:", e)The first line prints <class 'float'>. The second prints 3.10. The third raises TypeError, with the message unsupported operand type(s) for +: 'decimal.Decimal' and 'float'.
Four ways to turn a float into an integer
int() is only one of several functions that turn a float into an integer. They differ on negative numbers and on halves.
import math
for v in [3.9, -3.9, 2.5, -2.5]:
print(v, int(v), math.trunc(v), math.floor(v), math.ceil(v), round(v))| `v` | `int(v)` | `math.trunc(v)` | `math.floor(v)` | `math.ceil(v)` | `round(v)` |
|---|---|---|---|---|---|
| 3.9 | 3 | 3 | 3 | 4 | 4 |
| -3.9 | -3 | -3 | -4 | -3 | -4 |
| 2.5 | 2 | 2 | 2 | 3 | 2 |
| -2.5 | -2 | -2 | -3 | -2 | -2 |
int()andmath.trunc()cut off the fractional part, which moves the value toward zero.math.floor()always moves toward negative infinity, andmath.ceil()toward positive infinity. For negative numbers,floorandtruncdisagree.round()goes to the nearest integer. Exact halves go to the nearest even integer, so2.5becomes2and3.5becomes4.
The floor behavior matches //: -7 // 2 is -4, the same as math.floor(-3.5).
How round() works
round(x) with one argument returns an int. round(x, ndigits) returns the same type as x, so round(2.5, 0) is the float 2.0. A negative ndigits rounds to tens, hundreds and so on.
print(round(2.675, 2))
print(round(0.125, 2))
print(round(1250, -2))
print(round(1350, -2))
print(type(round(2.5)), type(round(2.5, 0)))This prints 2.67, 0.12, 1200, 1400, and then <class 'int'> <class 'float'>.
Two rules explain the first two results.
- Halves round to even. This is "banker's rounding". It stops a long list of rounded numbers from drifting upward.
0.125is exactly representable in binary, so it is a true tie, and the even digit2wins. - Python rounds the stored value, not the literal you typed. The float
2.675is stored as slightly less than 2.675, so it rounds down to2.67. No tie exists, and the result is correct for the stored number.
Truncating can lose a cent
A frequent bug converts money to integer cents with int().
price = 19.99
print(price * 100)
print(int(price * 100))
print(round(price * 100))The product is 1998.9999999999998. int() truncates it to 1998, which is one cent short. round() returns 1999. When a float should be a whole number and might be off by a tiny error, use round(). Better still, avoid floats for money, as the next section shows.
Rounding with Decimal
Decimal.quantize() rounds to a pattern, such as two decimal places. The rounding argument selects the rule. The default rule is ROUND_HALF_EVEN, the same tie behavior as round().
from decimal import Decimal, ROUND_HALF_UP
d = Decimal("0.125")
cent = Decimal("0.01")
print(d.quantize(cent))
print(d.quantize(cent, rounding=ROUND_HALF_UP))
print(Decimal(0.1))
print(Decimal(str(0.1)))
print(int(Decimal("3.9")))The output is:
0.12, from the default half-even rule.0.13, fromROUND_HALF_UP.0.1000000000000000055511151231257827021181583404541015625.0.1.3.
The third line shows that Decimal(0.1) converts the float's exact binary value, error included. Build decimals from strings (Decimal("0.1")). If you only have a float, Decimal(str(x)) uses the shortest text that identifies it. int(Decimal(...)) truncates toward zero, like int() on a float.
round() also works on a Decimal. With one argument it returns an int, and with ndigits it returns a Decimal.
Conversions that fail or lose information
Not every conversion is possible. Some are lossy and some raise errors.
print(float(2**53 + 1))
print(int(float(2**53 + 1)) == 2**53 + 1)
for bad in (float("inf"), float("nan")):
try:
int(bad)
except (OverflowError, ValueError) as e:
print(type(e).__name__ + ":", e)
try:
float(10**400)
except OverflowError as e:
print("OverflowError:", e)- A
floathas 53 bits of precision. Integers above2**53can lose their last digits. The first line prints9007199254740992.0, and the comparison printsFalse. int(float("inf"))raisesOverflowError: cannot convert float infinity to integer.int(float("nan"))raisesValueError: cannot convert float NaN to integer.- A Python
inthas no size limit, but a float does.float(10**400)raisesOverflowError: int too large to convert to float.
bool is a number
bool is a subclass of int. True equals 1 and False equals 0, and they take part in arithmetic. This is useful for counting, and it is a source of surprises.
from decimal import Decimal
print(int(True), float(False))
print(sum([True, False, True]))
print(type(True + 1), type(True + 1.5))
print(bool(0), bool(0.0), bool(Decimal("0")), bool("0"), bool(-1))The output is 1 0.0, then 2, then <class 'int'> <class 'float'>, then False False False True True.
bool(x) is False for zero of any numeric type and True for every other number. The string "0" is True, because any non-empty string is true. bool(float("nan")) is also True.
The counting idiom sum(n > 0 for n in numbers) works because each comparison gives a bool that sums as 0 or 1. The same rule hides bugs. True + True is 2, which is rarely what you meant.
Common mistakes
- Using
int()to round.int(2.9)is2. Useround()when you want the nearest integer. - Assuming
round()always rounds up on.5. It rounds ties to even, and it rounds the stored float, not your decimal literal. - Using
Decimal(0.1). Pass a string instead. - Mixing
Decimalandfloat. Convert deliberately withDecimal(str(x)), or keep the whole calculation in one type. - Treating a bool as a flag only.
Truecan silently join arithmetic and change a result. - Rounding too early. Round once, at the end of a calculation, or the errors accumulate.
Exercise
What do int(-2.7), math.floor(-2.7), round(-2.7) and round(0.5) print? Then say how you would round Decimal("2.345") to two places so that the result is 2.35.
Show answer
They print -2, -3, -3 and 0. int() truncates toward zero, floor goes toward negative infinity, round(-2.7) is the nearest integer, and 0.5 is a tie that rounds to the even integer 0. For the decimal, call Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) after from decimal import Decimal, ROUND_HALF_UP. The default half-even rule would give 2.34.
Exercise
A program computes int(4.35 * 100) and gets 434 instead of 435. Explain why, and give two fixes.
Show answer
The float 4.35 is stored as slightly less than 4.35, so 4.35 * 100 is 434.99999999999994, and int() truncates it to 434. One fix is round(4.35 * 100), which gives 435. The other is to avoid floats and use Decimal("4.35") * 100, which is exactly Decimal("435.00").