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

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

当前回答

我需要四舍五入到前面的5。

举个例子,16发到15发或者19发到15发

下面是使用的代码

    def myround(x,segment):
        preRound = x / segment
        roundNum = int(preRound)
        segVal = segment * roundNum
        return segVal

其他回答

def round_to_next5(n):
    return n + (5 - n) % 5

round(x[, n]):数值四舍五入到10的负n次方的最接近倍数。所以如果n是负的…

def round5(x):
    return int(round(x*2, -1)) / 2

由于10 = 5 * 2,您可以对2使用整数除法和乘法,而不是对5.0使用浮点除法和乘法。这并不重要,除非你喜欢位移位

def round5(x):
    return int(round(x << 1, -1)) >> 1

那么这个呢:

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

对已接受答案的补充,用于指定四舍五入到最接近的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