How do you round UP a number?
How does one round a number UP in Python?
I tried round(number)
but it rounds the number down. Example:
round(2.3) = 2.0
and not 3, as I would like.
The I tried int(number + .5)
but it round the number down again! Example:
int(2.3 + .5) = 2
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 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.
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 that's 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
If working with integers, one way of rounding up is to take advantage of the fact that //
rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.
rounded_up = -(-numerator // denominator)
For example:
>>> print(-(-101 // 5))
21
You might also like numpy:
>>> import numpy as np
>>> np.ceil(2.3)
3.0
I'm not saying it's better than math, but if you were already using numpy for other purposes, you can keep your code consistent.
Anyway, just a detail I came across. I use numpy a lot and was surprised it didn't get mentioned, but of course the accepted answer works perfectly fine.