Sub topic 3
Rounding numbers: floor, ceil, trunc, and round
This chapter assumes you can write Python functions and loops, know the difference between int and float, and have used import math before. It covers four ways to turn a number into a nearby whole number, or a number with fewer decimals. They give different answers for negative numbers, for halves, and for values like 2.675. You will learn what each one does, how to choose between them, and where each one fails.
The four tools at a glance
Python has three ways to move a number to an integer, and one general-purpose rounder.
math.floor(x)returns the largest integer less than or equal tox. It rounds toward negative infinity.math.ceil(x)returns the smallest integer greater than or equal tox. It rounds toward positive infinity.math.trunc(x)removes the fractional part. It rounds toward zero.round(x)returns the nearest integer. Whenxis exactly halfway between two integers, it picks the even one.
floor, ceil, and trunc live in the math module. round is a built-in function, so it needs no import.
import math
for x in [2.5, -2.5, 2.4, -2.4, 3.5]:
print(x, math.floor(x), math.ceil(x), math.trunc(x), round(x))
# 2.5 2 3 2 2
# -2.5 -3 -2 -2 -2
# 2.4 2 3 2 2
# -2.4 -3 -2 -2 -2
# 3.5 3 4 3 4For positive numbers, floor and trunc agree. For negative numbers, ceil and trunc agree. The functions differ only on the side of zero where the number sits, and that is where bugs hide.
Floor and ceil
floor and ceil both return an int, not a float. Python integers have no size limit, so you can use them on very large floats without overflow.
import math
print(math.floor(7.9)) # 7
print(math.ceil(7.1)) # 8
print(type(math.floor(7.9))) # <class 'int'>
print(math.floor(-0.1)) # -1
print(math.ceil(-0.9)) # 0Both functions leave integers unchanged. Both reject values that have no integer form:
import math
for bad in [float("inf"), float("nan")]:
try:
math.floor(bad)
except (OverflowError, ValueError) as exc:
print(type(exc).__name__, exc)
# OverflowError cannot convert float infinity to integer
# ValueError cannot convert float NaN to integerFloor division is floor
The // operator is floor division. It floors the true quotient, so for negative results it rounds away from zero:
import math
print(-7 // 2) # -4
print(math.floor(-7 / 2)) # -4
print(math.trunc(-7 / 2)) # -3
print(int(-7 / 2)) # -3This matches the rule that a == (a // b) * b + a % b. The remainder % takes the sign of the divisor. If you expected C-style division that cuts toward zero, use math.trunc(a / b) or int(a / b). For very large integers, a / b loses precision, so prefer an integer-only approach there.
Ceiling division for integers
A common task is "how many pages do I need?" The formula is the ceiling of n / size. With floats this works for small numbers:
import math
items = 23
per_page = 10
print(math.ceil(items / per_page)) # 3For large integers, items / per_page converts to a float and may lose precision. A pure-integer version avoids the problem by negating twice, so floor division acts as ceiling division:
items = 23
per_page = 10
pages = -(-items // per_page)
print(pages) # 3Trunc and int
math.trunc(x) drops the fractional part. For floats, int(x) does the same thing, so they give identical results.
import math
print(math.trunc(9.99)) # 9
print(math.trunc(-9.99)) # -9
print(int(-9.99)) # -9The difference is in intent and in what they accept. int("42") parses a string, but math.trunc("42") raises a TypeError. Use trunc when you want to say "cut off the decimals" and the input is already a number. Use int when you may also be converting strings.
You can also use trunc to cut to a fixed number of decimals by scaling first:
import math
price = 3.14159
cut = math.trunc(price * 100) / 100
print(cut) # 3.14This trick is only approximately right, because price * 100 is a float and may land just below a whole number. For example, 0.29 * 100 is 28.999999999999996, so truncating gives 28 rather than 29. For money, see the decimal section below.
The built-in round
round(x) rounds to the nearest integer and returns an int. round(x, n) rounds to n decimal places and returns a value of the same type as x.
print(round(3.14159)) # 3
print(round(3.14159, 2)) # 3.14
print(round(2.5)) # 2
print(round(2.5, 0)) # 2.0
print(round(-0.4)) # 0
print(round(-0.4, 0)) # -0.0Notice that round(2.5) returns an int while round(2.5, 0) returns a float. Passing any second argument, even 0, keeps the float type.
Ties go to the even neighbor
Python 3 uses round-half-to-even, also called banker's rounding. When a value is exactly halfway between two candidates, it chooses the one whose last digit is even.
print(round(0.5)) # 0
print(round(1.5)) # 2
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(-2.5)) # -2This is not a bug. If you always round halves up, a long list of values drifts upward, because every tie is pushed the same way. Rounding ties to even makes the errors cancel out on average. It is the default rule in the IEEE 754 floating-point standard.
If you were taught that .5 always rounds up, this behavior will surprise you. The next section explains why even more surprises can appear.
Negative ndigits
A negative second argument rounds to the left of the decimal point. It works on integers too.
print(round(1234, -2)) # 1200
print(round(1250, -2)) # 1200
print(round(1350, -2)) # 1400
print(round(1234.5, -1)) # 1230.0The tie rule still applies: 1250 is halfway between 1200 and 1300, and 1200 has the even hundreds digit.
To round to a multiple of something other than a power of ten, divide, round, and multiply back:
def round_to_multiple(x, step):
return round(x / step) * step
print(round_to_multiple(37, 5)) # 35
print(round_to_multiple(38, 5)) # 40
print(round_to_multiple(0.37, 0.25)) # 0.25Why round(2.675, 2) gives 2.67
Most decimal fractions cannot be stored exactly as binary floats. The literal 2.675 is stored as a number slightly below 2.675. When round is asked for two decimals, it sees a value just under the midpoint and rounds down.
from decimal import Decimal
print(round(2.675, 2)) # 2.67
print(Decimal(2.675))
# 2.67499999999999982236431605997495353221893310546875The same thing explains why round(0.285, 2) returns 0.28. round is working correctly on the number that is actually stored. The mismatch is between what you typed and what the hardware holds. The chapter on floating-point comparison covers this idea in more detail.
Values that are exact in binary, like 0.125, behave as the tie rule says:
print(round(0.125, 2)) # 0.12
print(round(0.375, 2)) # 0.38Rounding for display versus rounding for math
Formatting a number for output is separate from changing its value. Format specifiers use the same round-half-to-even logic on the stored binary value:
x = 2.675
print(f"{x:.2f}") # 2.67
print(f"{0.125:.2f}") # 0.12
print(f"{2.5:.0f}") # 2Round once, at the end. If you round intermediate results and then keep calculating, the small errors add up.
When you need "round half up"
Some domains, such as invoices and school grades, require ties to go up. Use the decimal module, which lets you pick the rule. Build the Decimal from a string so it holds exactly the digits you typed.
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
value = Decimal("2.675")
cent = Decimal("0.01")
print(value.quantize(cent, rounding=ROUND_HALF_UP)) # 2.68
print(value.quantize(cent, rounding=ROUND_HALF_EVEN)) # 2.68
print(Decimal("2.665").quantize(cent, rounding=ROUND_HALF_UP)) # 2.67
print(Decimal("2.665").quantize(cent, rounding=ROUND_HALF_EVEN)) # 2.662.675 rounds the same way under both rules, because the digit before the tie, 7, is odd and "even" means going up to 8. The 2.665 case shows the rules diverging. Half-up gives 2.67, and half-even keeps the even digit, giving 2.66.
Choosing a function
| Goal | Use | Example result for -2.5 |
|---|---|---|
| Largest whole number not above x | `math.floor(x)` | -3 |
| Smallest whole number not below x | `math.ceil(x)` | -2 |
| Remove the decimals | `math.trunc(x)` | -2 |
| Nearest whole number, ties to even | `round(x)` | -2 |
| Fixed decimals for display | `f"{x:.2f}"` | `-2.50` |
| Exact decimal rules (money) | `Decimal.quantize` | depends on rule |
Common errors
- Using
truncorintwhere you needflooron negative numbers. A bucket index such asint(x / width)puts-0.5in bucket 0 together with0.5. Usemath.floor(x / width)instead. - Expecting
round(2.5)to be 3. It is 2. - Expecting
round(x, 2)to match what you typed for values like2.675. - Passing
infornantofloor,ceil,trunc, orroundwithout a second argument, which raises an error. - Rounding at each step of a calculation instead of once at the end.
Practice
Exercise
Predict the output of math.floor(-3.2), math.ceil(-3.2), math.trunc(-3.2), and round(-3.5).
Show answer
-4, -3, -3, and -4. Floor goes toward negative infinity, ceil toward positive infinity, and trunc toward zero. For round(-3.5), the tie goes to the even neighbor, and -4 is even while -3 is odd.
Exercise
A list of 41 items is shown 8 per page. Write an integer-only expression for the number of pages, and give its value.
Show answer
-(-41 // 8) evaluates to 6. Floor division of -41 by 8 gives -6, and negating it gives 6. The last page holds one item.
Exercise
Why does round(2.675, 2) return 2.67 when the midpoint rule would suggest 2.68, and how can you get 2.68?
Show answer
The float 2.675 is stored as slightly less than 2.675, so it is not a true tie and rounds down. To get 2.68, use Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), with the Decimal built from a string.