简体   繁体   中英

Python3.3 rounding up

In Python I would like to divide two numbers and if the answer is not an integer I want the number to be rounded up to the number above.
For example 100/30 not to give 33.3 but to give 4. Can anyone suggest how to do this? Thanks.

You can use the math.ceil() function:

>>> import math
>>> math.ceil(100/33)
4

you can use the ceil function in math library that python has, but also you can take a look why in a logical sense

a = int(100/3) # this will round down to 3
b = 100/3 # b = 33.333333333333336, a and b are not equal

so we can generalize into the following

def ceil(a, b):
    if (b == 0):
        raise Exception("Division By Zero Error!!") # throw an division by zero error
    if int(a/b) != a/b:
        return int(a/b) + 1
    return int(a/b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM