Is there a built-in function that can round like the following?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
I don't know of a standard function in Python, but this works for me:
def myround(x, base=5):
return int(base * round(float(x)/base))
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(float(x)/5)
where float
is only needed in Python2), and then since we divided by 5, we multiply by 5 as well. The final conversion to int
is because round()
returns a floating-point value in Python 2.
I made the function more generic by giving it a base
parameter, defaulting to 5.