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,227
  • 4
  • 22
  • 30

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
  • 963,270
  • 265
  • 3,804
  • 3,187
0

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
  • 508
  • 7
  • 18