Python's number handling is close to PHP's, with one standout difference: Python integers have no size limit, growing as large as memory allows.
| Function | What it does | Example |
|---|---|---|
| round(n) | Rounds to the nearest whole number | round(4.5) → 4 (see the callout below) |
| round(n, decimals) | Rounds to a set number of decimal places | round(3.14159, 2) → 3.14 |
| math.floor(n) | Always rounds down | math.floor(4.9) → 4 |
| math.ceil(n) | Always rounds up | math.ceil(4.1) → 5 |
round(4.5) is not what you'd expect
Python's round() uses "round half to even" (also called banker's rounding) — round(4.5) gives 4, not 5, and round(5.5) gives 6. This is deliberately different from PHP's round(), which always rounds .5 up, and it surprises almost everyone the first time they hit it.
floor() and ceil(), along with most other math functions, live in Python's math module rather than being available by default — you'll look at import properly in an upcoming lesson, but the pattern is simple enough to use right away:
import math
print(math.floor(4.9)) # 4
print(math.ceil(4.1)) # 5
print(math.sqrt(64)) # 8.0
print(math.pi) # 3.141592653589793print(abs(-7)) # 7 — absolute value
print(max(3, 9, 2)) # 9 — largest of the arguments
print(min(3, 9, 2)) # 2 — smallest of the arguments
print(pow(2, 10)) # 1024 — same as 2 ** 10An f-string with a format specifier is the standard way to control decimal places and add thousands separators:
value = 1234567.891
print(f"{value:,.2f}") # "1,234,567.89"