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 OverflowThe 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.
Videos
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 ☺
round (0.5) = 0
round (1.5) = 2
round (2.5) = 2
round (3.5) = 4
Is it just me or does this feel like some sort of inconsistency? Why does 0.5 round to 0, when it should round to 1?
edit: it's because python uses https://en.wikipedia.org/w/index.php?title=IEEE_754#Rounding_rules
edit2: Surprised this got this much attention. Here's a code work-around someone made:
def col_round(x): frac = x - math.floor(x) if frac < 0.5: return math.floor(x) return math.ceil(x)