89DEVs

Python: How to round to nearest 5 (or other number)?

How to round to 5 (or any other number)

Use a custom function, because Python doesn't offer a built-in function to round to 5 (or any other number). The function returns the base * round(num/base). The goal is to round to whole numbers with steps of 5: 10 -> 10 11 -> 10 12 -> 10 13 -> 15 14 -> 15 15 -> 15 16 -> 15 17 -> 15 18 -> 20 19 -> 20 20 -> 20 Define a function that accepts the number and a base as optional second argument. It then returns the rounded number. # round to nearest 5 def round_to_step(num, base=5): return base * round(num/base) print(round_to_step(57)) The function returns as expected 55. 55 The second argument can be used to change the base to 10 or any other number. # round to step function def round_to_step(num, base=5): return base * round(num/base) print(round_to_step(57, 10)) The function returns now 60 instead of 55 because we round to base of 10. 60

Other rounding operations in Python

Python offers a variety of other rounding operations: To round up use math.ceil() or numpy.ceil() methods. To round down use the int() function or the math.floor() method. To round to nearest integer use the round() function or numpy.round(). To round to 2 decimals use the built-in round() function.

                
        

Summary


Click to jump to section