Question

Is it possible to round upwords using the built-in math module? I know that you can use math.floor() to round down, but is there a way to round up? Currently, I use this to round:

def roundTo32(x, base=32):
    return int(base * round(float(x) / base))

but that doesn't always round up.

Was it helpful?

Solution

Use math.ceil() to round float values up:

import math

def roundTo32(x, base=32):
    return int(base * math.ceil(float(x) / base))

Demo:

>>> import math
>>> def roundTo32(x, base=32):
...     return int(base * math.ceil(float(x) / base))
... 
>>> roundTo32(15)
32
>>> roundTo32(33)
64

OTHER TIPS

If you want to only use integers, you can also do:

def roundTo32(x):
    return (x + 31) & ~31

the part & ~31 is possible because 32 is a power of two.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top