python – How do you round UP a number?

python – How do you round UP a number?

The ceil (ceiling) function:

import math
print(int(math.ceil(4.2)))

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)
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.

python – How do you round UP a number?

python – How do you round UP a number?

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.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:

console.log(Math.ceil(4500/1000));
5

Leave a Reply

Your email address will not be published.