是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
当前回答
divround的修改版本:-)
def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
其他回答
对不起,我想对阿洛克辛格海的回答发表评论,但由于缺乏声誉,它不让我评论=/
总之,我们可以再归纳一步:
def myround(x, base=5):
return base * round(float(x) / base)
这允许我们使用非整数进制,如。25或任何其他分数进制。
对于整数和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]
舍入到非整数值,例如0.05:
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
我发现这很有用,因为我只需要在代码中进行搜索和替换,就可以将“round(”更改为“myround(”,而不必更改参数值。
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
我不知道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))