round() is Python's built-in function for rounding numbers. It uses "round half to even" (also known as bankers' rounding), meaning numbers ending in .5 are rounded to the nearest even integer. For example:
round(2.5)→2round(3.5)→4
To round to a specific number of decimal places, pass the desired number as the second argument:
round(3.14159, 2)→3.14
For rounding up to the nearest integer, use math.ceil():
import math; math.ceil(3.2)→4
For rounding down, use math.floor():
import math; math.floor(3.7)→3
To round up to a specific decimal place, combine multiplication, math.ceil(), and division:
import math
def round_up(num, dec=0):
mult = 10 ** dec
return math.ceil(num * mult) / mult
round_up(2.543, 2) # → 2.55The math module provides ceil(), floor(), and trunc() for precise control over rounding behavior.
The math.ceil (ceiling) function returns the smallest integer higher or equal to x.
For Python 3:
import math
print(math.ceil(4.2))
For Python 2:
import math
print(int(math.ceil(4.2)))
Answer from Steve Tjoa on Stack OverflowVideos
The math.ceil (ceiling) function returns the smallest integer higher or equal to x.
For Python 3:
import math
print(math.ceil(4.2))
For Python 2:
import math
print(int(math.ceil(4.2)))
I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me.
>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5
The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.
Greetings,
Code: x = round(7.85, 2) print(x)
Result: 7.8
Why is that? Rounding down starts at 0 and ends at 4, and rounding up begins at 5 and ends at 9. The result should be 7.9.
Does Python have its own math rules? If so, why? Math is math...
Please and thank you ☺