How to round up with Python?

Asked

Viewed 16,658 times

4

Is there a native Python way to top up?

Example: 10/3 resulting 4.

What I’m wearing now is a parole:

x=10  
if x % 3 != 0:  
    x += 1  

But that’s not very practical.

  • 1

    In the Python3 the division returns a value float, with this it is possible to round up pro value using the method built-in round() (e. g round(3/2) = 1.5, soon becomes 2)

3 answers

7


Using pure math whenever you want to round a number up add an entire unit of the value whatever the rounding is done and take the whole part, this will ensure that it will always fall to the next value. But there’s a problem that the question deals with, when it’s already integer you can’t do the sum, so there’s no escape from it:

x = x + (1 if x % int(x) else 0)

If you wish you can use a ready-made Python function which is ceil() that knocks on the ceiling:

x = ceil(x)

I put in the Github for future reference.

But note that this has some criteria, and they may even be more suitable if you understand them. It may give a different result if it is negative or positive.

In the background the function will do these checks for you, it’s not that you’re doing less, it’s just abstracting for you.

4

Try to use the function math.ceil().

x = 10
x= x % 3
x = ceil(x)

0

I was having the same doubt and I parachuted in here about the code above:

x = x + (1 if x % int(x) else 0)

This case works very well in most cases , but when we test with a generic 'P' entry belonging to the range [0, 1), the code does not perform :

  Traceback (ZeroDivisionError: float modulo)

I made an adaptation for personal use and will post here to help other people:

def Arredonda(x):    
    return  0 if not x else (int(x + (1 if int(x) % x == int(x) else 0)))

There’s another simpler way I figured out while trying to remember the code above:

def Arredonda(n):
    return int(n + (0 if n % 1 ==  0 else 1)) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.