How do you round a number in Python?
Short answer: use round(). round(3.78) returns 4, and round(3.14159, 2) returns 3.14. To always round up, use math.ceil(), and to always round down, use math.floor().
import math
print(round(3.78)) # 4
print(round(3.14159, 2)) # 3.14
print(math.ceil(3.21)) # 4 always up
print(math.floor(3.78)) # 3 always downWatch out for exact halves: round(2.5) returns 2, not 3, because Python rounds halves to the nearest even number.
round() goes to the nearest value, halves go to the even number, math.ceil() rounds up and math.floor() rounds down.
Every way to round in Python
| What you want | Code | Result |
|---|---|---|
| Nearest integer | round(3.78) | 4 |
| Two decimals | round(3.14159, 2) | 3.14 |
| Always up | math.ceil(3.21) | 4 |
| Always down | math.floor(3.78) | 3 |
| Drop the decimals | math.trunc(-3.7) or int(-3.7) | -3 |
| To the nearest hundred | round(1234.5678, -2) | 1200.0 |
| Halves always up (money) | Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP) | 2.68 |
| Only for display | f"{3.14159:.2f}" | "3.14" |
| A NumPy array or pandas column | np.round(arr, 1), df["col"].round(1) | Each value rounded |
Round to the nearest integer or to decimals with round()
round(number, ndigits) takes two arguments:
number: the value you want to round.ndigits(optional): how many decimals to keep. If you leave it out, you get an integer.
price = 19.4567
print(round(price)) # 19 int
print(round(price, 2)) # 19.46 float
print(round(price, 0)) # 19.0 float
print(round(1234.5678, -2)) # 1200.0Without ndigits, round() returns an int. With ndigits, even 0, it returns a float. A negative ndigits rounds to tens, hundreds or thousands.
