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

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

当前回答

def round_up_to_base(x, base=10):
    return x + (base - x) % base

def round_down_to_base(x, base=10):
    return x - (x % base)

这给了

基础= 5:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]

>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

基础= 10:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

在Python 3.7.9中测试

其他回答

如果有人需要“财务四舍五入”(0.5位总是向上):

def myround(x, base=5):
    roundcontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
    decimal.setcontext(roundcontext)
    return int(base *float(decimal.Decimal(x/base).quantize(decimal.Decimal('0'))))

根据文档,其他舍入选项是:

ROUND_CEILING(朝向无限) ROUND_DOWN(趋近于零) ROUND_FLOOR(朝向-∞) ROUND_HALF_DOWN(当平局趋于0时最接近) ROUND_HALF_EVEN(最接近偶数) ROUND_HALF_UP(到最接近的平局从0开始) ROUND_UP(远离零) ROUND_05UP(如果四舍五入后的最后一位为0或5,则远离0;否则趋于零)

默认情况下,Python使用ROUND_HALF_EVEN,因为它有一些统计优势(四舍五入的结果没有偏见)。

对于整数和Python 3:

def divround_down(value, step):
    return value//step*step


def divround_up(value, step):
    return (value+step-1)//step*step

生产:

>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

我不知道Python中的标准函数,但这对我来说是可行的:

Python 3

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

很容易理解为什么上面的方法是有效的。你要确保你的数字除以5是一个整数,四舍五入正确。所以,我们首先做的就是(round(x/5))然后因为我们除以5,所以我们也乘以5。

我通过给它一个基本参数使函数更通用,默认值为5。

Python 2

在Python 2中,需要使用float(x)来确保/执行浮点除法,并且需要最终转换为int,因为在Python 2中round()返回的是浮点值。

def myround(x, base=5):
    return int(base * round(float(x)/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