Is there a built-in function that can round like the following?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t know of a standard function in Python, but this works for me:
Python 3
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
baseparameter, defaulting to 5.Python 2
In Python 2,
float(x)would be needed to ensure that/does floating-point division, and a final conversion tointis needed becauseround()returns a floating-point value in Python 2.