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

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

当前回答

舍入到非整数值,例如0.05:

def myround(x, prec=2, base=.05):
  return round(base * round(float(x)/base),prec)

我发现这很有用,因为我只需要在代码中进行搜索和替换,就可以将“round(”更改为“myround(”,而不必更改参数值。

其他回答

这只是一个比例的问题

>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
...     int(round(b/5.0)*5.0)
... 
10
10
10
15
15
15
15
15
20
20
20

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 round_to_next5(n):
    return n + (5 - n) % 5

如果有人需要“财务四舍五入”(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,因为它有一些统计优势(四舍五入的结果没有偏见)。

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

import math

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