How do you round UP a number?
Asked Answered
F

31

804

How does one round a number UP in Python?

I tried round(number) but it rounds the number down. Here is an example:

round(2.3) = 2.0 

and not 3, as I would like.

Then I tried int(number + .5) but it round the number down again! Example:

int(2.3 + .5) = 2
Floriaflorian answered 1/3, 2010 at 14:40 Comment(1)
round(number + .5) doesn't work if the number is integer. round(3+.5) == 4, when you actually want 3.Ellaelladine
T
1311

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)))
Thisbee answered 1/3, 2010 at 14:40 Comment(6)
Elaboration: math.ceil returns the smallest integer which is greater than or equal to the input value. This function treats the input as a float (Python does not have strongly-typed variables) and the function returns a float. If you want an int, you can construct an int from the return value, i.e., int(math.ceil(363))Principally
@Sinnet: Actually one could say that python is strongly typed https://mcmap.net/q/55196/-is-python-strongly-typedBrownley
@TheEspinosa: Yes, python is definitely strongly typed, its just that many functions ask questions about the type of some parameters and execute different code depending on the answer.Charbonnier
@R.W.Sinnet In Python 3, math.ceil returns an actual integer object, not just floating object with integer value.Topliffe
Take care of float precision, due to 10000000 * 0.00136 = 13600.000000000002 ceil can increase a lot math.ceil(10000000 * 0.00136) = 13601.0Culp
@Ender "the function outputs a float" is not correct except in ancient, no-longer-supported versions of Python. In Python 3, math.ceil returns an int.Forceps
O
330

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.

Ovalle answered 11/5, 2014 at 7:28 Comment(4)
Nice. You can also use // for integer division, so this becomes 21 // 5 + (21 % 5 > 0).Entanglement
...and to have it as a nice function: def round_up(number): return int(number) + (number % 1 > 0)Loudish
but you would have to do a bit much of calculation for that, right? I know, you don't care, neither do I unless I really do.Upanishad
Also the integrated divmod function can be used for this: d, m = divmod(number) return int(d) + m > 0Loos
Z
201

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
Zn answered 1/2, 2016 at 8:23 Comment(4)
What about when you don't need to perform any math operation? I.e. you just have one number.Vandal
@Klik: then you can just divide by 1 ==> -( -num // 1) and you are getting your answer :-) Have a nice day! David Bau: very nice proposal!Jaggy
Nice! I've always used (num + den - 1) // den, which is fine for int inputs with positive denominators, but fails if even a single non-integral float is involved (either numerator or denominator); this is more magical looking, but works for both ints and floats. For small numerators, it's also faster (on CPython 3.7.2), though oddly, when only the numerator is large enough that array based math is needed, your approach is slower; not clear why this is, since the division work should be similar and two unary negations should be cheaper than addition + subtraction.Polyphemus
The fact that it doesn't need any import and is fast makes it exactly what i was looking for.Thornton
P
180

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
Pontonier answered 31/10, 2011 at 6:39 Comment(2)
In Python 2.x : int/int --> int and int/float --> float In Python 3.x : int/int can result in a floatJennifferjennilee
you can get the Python 3.x on behavior on certain versions of Python 2.x by enabling "true division" as shown hereEpileptic
H
88

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.

Huss answered 26/4, 2013 at 16:27 Comment(2)
Using numpy is nice too. The easiest would be with math since it is already part of python built in libraries. It makes more sense. Instead as you mentioned if you use a lot numpy for other issues, then it makes sense and consistent to use numpy.ceil :-) Good hint!Jaggy
If you are using pandas and imported the whole module as pd, then just use pd.np.ceil(2.3). No need for a separate numpy import.Cabezon
C
40

Use math.ceil to round up:

>>> import math
>>> math.ceil(5.4)
6.0

NOTE: The input should be float.

If you need an integer, call int to convert it:

>>> int(math.ceil(5.4))
6

BTW, use math.floor to round down and round to round to nearest integer.

>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)
Carlita answered 1/3, 2010 at 14:41 Comment(2)
The input does not necessarily need to be a float if using python 3: ceil() will take care of it internallyGoby
Note that in python 3, round() will actually round half to even as described in the docs so the second line will return (4, 4, 5, 6)Lotuseater
C
29

I am surprised nobody suggested

(numerator + denominator - 1) // denominator

for integer division with rounding up. Used to be the common way for C/C++/CUDA (cf. divup)

Crosson answered 8/4, 2017 at 9:52 Comment(3)
Relevant only for statically typed languages. If the denominator is a float you're dead.Murr
This also only works consistently if the denominator is positive; if the denominator is negative, you need to add 1 instead of subtracting it, or flip the signs of both numerator and denominator before performing the math.Polyphemus
@Murr obviously not true. Python has types and you may even check it for a value. This code will work fine for int. This is also worth noting that this code will work even for integers greater than 2^53 in which case floating point arithmetic might fail to produce correct result.Setsukosett
C
18

Here is a way using modulo and bool

n = 2.3
int(n) + bool(n%1)

Output:

3
Corrigible answered 20/3, 2022 at 22:30 Comment(1)
upvoted for not needing an importHendren
S
14

The syntax may not be as pythonic as one might like, but it is a powerful library.

https://docs.python.org/2/library/decimal.html

>>> from decimal import Decimal, ROUND_UP
>>> Decimal(1.2).quantize(Decimal("1"), ROUND_UP)
Decimal('2')
>>> int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP))
3
Smacker answered 27/3, 2015 at 19:21 Comment(0)
C
14

For those who want to round up a / b and get integer:

Another variant using integer division is

def int_ceil(a, b):
    return (a - 1) // b + 1

>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5

Note: a and b must be non-negative integers

Crawford answered 16/3, 2018 at 23:52 Comment(5)
Gives wrong answer for int_ceil(-0.1, 1). Should be 0.0 when it's -1.0Gymkhana
@ogogmad it makes sense only if a and b are integers. If you have float, use math.ceil as the top answer suggestsCrawford
int_ceil(2,-1) gives 0 for me. So the integers have to be non-negativeGymkhana
@ogogmad I agree, added note to the answer, thank youCrawford
@Crawford Isn't it enough that b is positive?Stakhanovism
C
11

Try this:

a = 211.0
print(int(a) + ((int(a) - a) != 0))
Cathepsin answered 4/12, 2017 at 22:22 Comment(2)
Clever. The ((int(a) - a) != 0) expression returns 1 whenever a needs to be rounded up. You may want to expand your answer and explain how this work.Materi
@TomAranda Can anyone explain how a boolean expression evaluates to a value please?Falcon
K
9

In case anyone is looking to round up to a specific decimal place:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier
Keeleykeelhaul answered 8/2, 2020 at 17:34 Comment(0)
E
7

Be shure rounded value should be float

a = 8 
b = 21
print math.ceil(a / b)
>>> 0

but

print math.ceil(float(a) / b)
>>> 1.0
Ecesis answered 30/7, 2014 at 19:27 Comment(0)
E
7

The above answers are correct, however, importing the math module just for this one function usually feels like a bit of an overkill for me. Luckily, there is another way to do it:

g = 7/5
g = int(g) + (not g.is_integer())

True and False are interpreted as 1 and 0 in a statement involving numbers in python. g.is_interger() basically translates to g.has_no_decimal() or g == int(g). So the last statement in English reads round g down and add one if g has decimal.

Ellaelladine answered 5/5, 2017 at 3:23 Comment(3)
And if you feel fancy, you can use int(g) + (g % 1 > 0) instead ;-)Ellaelladine
from math import ceil seems to fix importing the entire math module :)Diazotize
@Diazotize I'm afraid that line isn't much different to import math in terms of what happens behind the scenes. It just drops all symbols except ceil.Ellaelladine
A
6

Without importing math // using basic envionment:

a) method / class method

def ceil(fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

def ceil(self, fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

b) lambda:

ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)
Alienage answered 19/11, 2017 at 12:9 Comment(0)
G
6

x * -1 // 1 * -1

Confusing but it works: For x=7.1, you get 8.0. For x = -1.1, you get -1.0

No need to import a module.

Gymkhana answered 24/8, 2021 at 16:38 Comment(2)
Nice, but what's the logic behind it?Semitropical
x * -1 // 1 * -1 = -(-x // 1). The // operator always rounds down, so x // 1 = floor(x). Therefore, the logic here to round the negated number down, then negate again, which results in rounding up the original number.Cutout
F
5
>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.

Frowsty answered 21/6, 2018 at 14:16 Comment(1)
What if your number is 3, then it would round up to 4 which may or may not be what someone wantsEpizootic
C
2

For those who doesn't want to use import.

For a given list or any number:

x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]

You must first evaluate if the number is equal to its integer, which always rounds down. If the result is True, you return the number, if is not, return the integer(number) + 1.

w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]

Math logic:

  • If the number has decimal part: round_up - round_down == 1, always.
  • If the number doens't have decimal part: round_up - round_down == 0.

So:

  • round_up == x + round_down

With:

  • x == 1 if number != round_down
  • x == 0 if number == round_down

You are cutting the number in 2 parts, the integer and decimal. If decimal isn't 0, you add 1.

PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment.

Cyclades answered 10/1, 2021 at 19:14 Comment(0)
O
1

To do it without any import:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3
Orchestrion answered 15/6, 2014 at 0:34 Comment(0)
S
1

If you don't want to import anything, you can always write your own simple function as:

def RoundUP(num):
    if num== int(num):
        return num
    return int(num + 1)
Scissile answered 19/3, 2017 at 13:49 Comment(1)
This does not work if num is 2.05. You have to have at least as many digits with a 9 as your input, leaving you with a 0.999... which is 1. But then your corner case 2 is rounded up again. -- Well, I guess there is a reason why math.ceil is there.Spirochaetosis
U
1

I have a simple approach, based on fact that default round() almost does the job for us. We action in case it decreased the argument.

def round_up(arg):
    if arg > round(arg):
        return round(arg) + 1
    else:
        return round(arg)

It does

1 to 1     -1 to -1     1.0 to 1    1.00000001 to 2    -1.00000001 to -1
Ulberto answered 7/4, 2023 at 12:29 Comment(1)
Alternativ you could also do like this ''' def round_up(arg): if arg % 2: arg = int(arg ) + 1 return arg '''Idolist
Q
0

I know this is from quite a while back, but I found a quite interesting answer, so here goes:

-round(-x-0.5)

This fixes the edges cases and works for both positive and negative numbers, and doesn't require any function import

Cheers

Quark answered 14/1, 2015 at 8:15 Comment(2)
This will still rounds down -round(-x-0.3) = xMoffett
Also incorrectly increments exact numbers. Eg, -round(-3-0.5) returns 4 rather than 3, as it should.Farmhand
V
0

I'm surprised I haven't seen this answer yet round(x + 0.4999), so I'm going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.

Without importing, I use:

def roundUp(num):
    return round(num + 0.49)

testCases = list(x*0.1 for x in range(0, 50))

print(testCases)
for test in testCases:
    print("{:5.2f}  -> {:5.2f}".format(test, roundUp(test)))

Why this works

From the docs

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice

Therefore 2.5 gets rounded to 2 and 3.5 gets rounded to 4. If this was not the case then rounding up could be done by adding 0.5, but we want to avoid getting to the halfway point. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.

Vandal answered 8/9, 2016 at 6:31 Comment(3)
Using 0.4999, it will fail to give a correct result for any input in between ???.0000 and ???.0001 (open interval), not just exactly ???.0001. For instance, if you try it with 3.00005, you will get a result of 3 instead of the expected 4. Of course you can decrease the likelihood of this happening by adding more and more digits up to the maximum precision of floats, but what's the point to that if there are more robust and intuitive solutions at hand, like using math.ceil()?Impeditive
@Impeditive In my answer I state Without importing I use:. I've also mentioned that it will fail if the x + 0.4999 is equal to [n].5000.Vandal
Yes, you state in your answer that your solution is without importing, but I don't see the value of it. The math module and math.ceil() is in the standard library, so available everywhere for all practical purposes without installing extra stuff. And regarding your mention of when it fails, this is incomplete in your answer, as it fails for a whole interval, not just for a single point. Technically, you could argue you are correct, as you say if and not iff, but it will make the impression on the casual reader that it is less likely than it really is.Impeditive
D
0

You could use round like this:

cost_per_person = round(150 / 2, 2)

  
Dobson answered 26/12, 2020 at 16:27 Comment(1)
This should work when the second argument of round() is zero. That is round(x/y,0)Hawkins
P
-1

You can use floor devision and add 1 to it. 2.3 // 2 + 1

Phenica answered 20/7, 2016 at 7:7 Comment(2)
or use ceil() instead of weirdly doing the opposite and then compensatingGoby
This won't work. For example: from math import ceil; assert 4 // 2 + 1 == ceil(4 / 2)Nagana
M
-1

when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically: 4500/1000 = 4.5 --> int(4.5) = 4 and ceil of 4 obviouslly is 4

using 4500/1000.0 the result will be 4.5 and ceil of 4.5 --> 5

Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as "numeric type" and return a result directly as float

Good Luck!!

Mcanally answered 27/4, 2017 at 16:46 Comment(1)
That's only true in Python 2.x. In Python 3, division with a single / always results in a float, so 4500/1000 is always 4.5.Ellaelladine
S
-1

Incase you don't want to use math, use the floor division operator //. Floor division will always take the floor or the lower number.

Problem Example:

x = 5.5
x //= 1
print(x)

Output: 5.0

Solution: Add 1

x //= 1 + 1
print(x)

Output: 6.0

You can then typecast it to int or round() it if needed.

Signac answered 18/1 at 12:27 Comment(1)
This doesn't work.Republican
S
-2

This should work.

a=16
b= int(input("Please enter a number greater than 0 \n"))

if b==0:
    print ( "Wrong input")

elif a%b != 0:
    c=a/b
    d= int(c)+1
    print (c)
    print (d)
else:
    c=a/b
    d=c        
print (c)
print (d)
Suttle answered 1/4, 2023 at 15:23 Comment(1)
This question is over 13 years old and has dozens of existing answers. Are you entirely sure that your answer brings something new? If so, great! But please explain that to us.Convocation
A
-3

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2
Alcoholicity answered 14/3, 2018 at 19:12 Comment(1)
"rounding up" means that e.g. 2.3 gets turned into 3, which happens in neither of your examples.Ellaelladine
P
-3

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20
Phalanger answered 21/11, 2018 at 15:2 Comment(1)
Please explain what you are trying to do?Heurlin
L
-4

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

round(integer) + 1
Latialatices answered 1/6, 2016 at 2:46 Comment(2)
This will not work for any integer i where 2.5 < integer < 3. The desired value after rounding up is 3 but your expression will turn it into 4.Canonical
I think you mean round(integer + 0.5) This is what I often doVandal

© 2022 - 2024 — McMap. All rights reserved.