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

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

当前回答

对已接受答案的补充,用于指定四舍五入到最接近的5或其他值

import math

def my_round(x, base, down = True):
    return base * math.floor(x/base) + (not down) * base

其他回答

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 rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

下一个5的倍数

考虑51需要转换为55:

code here

mark = 51;
r = 100 - mark;
a = r%5;
new_mark = mark + a;

对已接受答案的补充,用于指定四舍五入到最接近的5或其他值

import math

def my_round(x, base, down = True):
    return base * math.floor(x/base) + (not down) * base