Skip to content

Python round to nearest 5

  • by

Use the round() function to round to the nearest 5 in Python. This function accepts two parameters: the first is a number and the second is the number of decimals to which to round the number.

round(number, 5)

Python doesn’t come built-in with a function that allows us to round a number to a given multiple, it may be helpful to build your own.

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

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.

Python round to the nearest 5 example

Simple example code.

def round_to_multiple(number, multiple):
    return multiple * round(number / multiple)

print(round_to_multiple(11, 5))

print(round_to_multiple(199, 5))


Python round to nearest 5

Do comment if you have any doubts or suggestions on this Python round topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading