在Python中按5(或其他数字)取整

258 投票
23 回答
227600 浏览
提问于 2025-04-15 19:20

有没有什么内置的函数可以像下面这样进行四舍五入?

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

23 个回答

26

这只是一个关于缩放的问题。

>>> 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
82

对于四舍五入到非整数值,比如0.05:

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

我觉得这个方法很有用,因为我只需要在我的代码中搜索并替换,把“round(”改成“myround(”,就不用去改参数的值了。

476

我不知道Python有没有标准的函数可以做到这一点,但这个方法对我有效:

Python 3

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

很容易理解为什么上面的代码能工作。你想确保你的数字除以5后是一个整数,并且是正确四舍五入的。所以,我们首先做这个操作(round(x/5)),然后因为我们是除以5,所以最后还要乘以5。

我把这个函数做得更通用了一点,给它加了一个base参数,默认值是5。

Python 2

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

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

撰写回答