是否可以使用内置数学模块对单词进行四舍五入?我知道你可以使用 math.floor() 向下舍入,但是有没有办法向上舍入?目前,我用它来舍入:
def roundTo32(x, base=32):
return int(base * round(float(x) / base))
但这并不总是四舍五入。
最佳答案
使用math.ceil()
将浮点值向上舍入:
import math
def roundTo32(x, base=32):
return int(base * math.ceil(float(x) / base))
演示:
>>> import math
>>> def roundTo32(x, base=32):
... return int(base * math.ceil(float(x) / base))
...
>>> roundTo32(15)
32
>>> roundTo32(33)
64
关于python - 如何使用数学模块(Python 3)四舍五入到 32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101070/