How do you round UP a number?

PythonFloating PointIntegerRounding

Python Problem Overview


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

Python Solutions


Solution 1 - Python

The ceil (ceiling) function:

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

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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)

Solution 7 - Python

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)

Solution 8 - Python

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 *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))

Solution 9 - Python

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

Solution 10 - Python

Try this:

a = 211.0
print(int(a) + ((int(a) - a) != 0))

Solution 11 - Python

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

Solution 12 - Python

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.

Solution 13 - Python

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)

Solution 14 - Python

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.

Solution 15 - Python

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

Solution 16 - Python

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.

Solution 17 - Python

Here is a way using modulo and bool

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

Output:

3

Solution 18 - Python

You could use round like this:

cost_per_person = round(150 / 2, 2)

  

Solution 19 - Python

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.

Solution 20 - Python

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

Solution 21 - Python

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

Solution 22 - Python

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.

Solution 23 - Python

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)

Solution 24 - Python

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

Solution 25 - Python

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!!

Solution 26 - Python

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

Solution 27 - Python

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

Solution 28 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbodacydoView Question on Stackoverflow
Solution 1 - PythonSteve TjoaView Answer on Stackoverflow
Solution 2 - Pythonuser3074620View Answer on Stackoverflow
Solution 3 - PythonTrophyGeekView Answer on Stackoverflow
Solution 4 - PythonDavid BauView Answer on Stackoverflow
Solution 5 - PythonLisaView Answer on Stackoverflow
Solution 6 - PythonkennytmView Answer on Stackoverflow
Solution 7 - PythonAndreas SchuhView Answer on Stackoverflow
Solution 8 - PythonNuclearPeonView Answer on Stackoverflow
Solution 9 - PythonPavelView Answer on Stackoverflow
Solution 10 - Pythonuser3712978View Answer on Stackoverflow
Solution 11 - PythonAlexeyView Answer on Stackoverflow
Solution 12 - PythonNearooView Answer on Stackoverflow
Solution 13 - PythonKuřátko ZvykView Answer on Stackoverflow
Solution 14 - PythonPonasMView Answer on Stackoverflow
Solution 15 - PythonosuwirelessView Answer on Stackoverflow
Solution 16 - PythonwladView Answer on Stackoverflow
Solution 17 - Pythonrhug123View Answer on Stackoverflow
Solution 18 - PythonThiagoView Answer on Stackoverflow
Solution 19 - PythonBESSView Answer on Stackoverflow
Solution 20 - PythonAndrey AntipovView Answer on Stackoverflow
Solution 21 - PythonFenmazView Answer on Stackoverflow
Solution 22 - PythonKlikView Answer on Stackoverflow
Solution 23 - PythonSebinView Answer on Stackoverflow
Solution 24 - Pythonuser6612280View Answer on Stackoverflow
Solution 25 - Pythonerick vicenteView Answer on Stackoverflow
Solution 26 - PythonSooBin KimView Answer on Stackoverflow
Solution 27 - PythonandresView Answer on Stackoverflow
Solution 28 - PythonDanielView Answer on Stackoverflow