python – How do you round UP a number?

python – How do you round UP a number?

The ceil (ceiling) function:

import math

I know this answer is for a question from a while back, but if you dont want to import math and you just want to round up, this works for me.

>>> int(21 / 5)
>>> int(21 / 5) + (21 % 5 > 0)

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.

python – How do you round UP a number?

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
>>> math.ceil(4500/1000.0)

The problem is that dividing two ints in python produces another int and thats truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.

In javascript, the exact same code produces a different result:


Leave a Reply

Your email address will not be published. Required fields are marked *