I don't know of a standard function in Python, but this works for me:
Python 3
def myround(x, base=5):
return base * round(x/base)
It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(x/5)
), and then since we divided by 5, we multiply by 5 as well.
I made the function more generic by giving it a base
parameter, defaulting to 5.
Python 2
In Python 2, float(x)
would be needed to ensure that /
does floating-point division, and a final conversion to int
is needed because round()
returns a floating-point value in Python 2.
def myround(x, base=5):
return int(base * round(float(x)/base))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…