1

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.

Pip
  • 4,387
  • 4
  • 23
  • 31

2 Answers2

3

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

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.

user666412
  • 528
  • 8
  • 18