是否有一个内置函数可以像下面这样舍入?

10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

当前回答

去掉“rest”会起作用:

rounded = int(val) - int(val) % 5

如果该值是一个整数:

rounded = val - val % 5

作为函数:

def roundint(value, base=5):
    return int(value) - int(value) % int(base)

其他回答

另一种方法(不需要显式的乘法或除法运算符):

def rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

那么这个呢:

 def divround(value, step):
     return divmod(value, step)[0] * step

divround的修改版本:-)

def divround(value, step, barrage):
    result, rest = divmod(value, step)
    return result*step if rest < barrage else (result+1)*step
def round_to_next5(n):
    return n + (5 - n) % 5

对不起,我想对阿洛克辛格海的回答发表评论,但由于缺乏声誉,它不让我评论=/

总之,我们可以再归纳一步:

def myround(x, base=5):
    return base * round(float(x) / base)

这允许我们使用非整数进制,如。25或任何其他分数进制。