38

Is there a function in Python that allows me to round down to the nearest multiple of an integer?

round_down(19,10)=10
round_down(19,5)=15
round_down(10,10)=10

I conscientiously looked at SO and found nothing related to rounding down to a nearest base. Please keep this in mind before you post links to related questions or flag as duplicate.

The Unfun Cat
  • 26,783
  • 25
  • 102
  • 145
  • If you found something to round up, why not using that and subtract one if the result and the original value are unequal? – Jonas Schäfer Oct 26 '12 at 07:33
  • 3
    I could have done it a million ways. I wanted a Python function to avoid littering my code with definitions, but I guess nothing to do this is included in Python and now I know. IG's answer looks pretty good though. – The Unfun Cat Oct 26 '12 at 07:39
  • Possible duplicate of [Round to 5 (or other number) in python](https://stackoverflow.com/questions/2272149/round-to-5-or-other-number-in-python) – Cristian Ciupitu Sep 23 '17 at 05:53

3 Answers3

92
def round_down(num, divisor):
    return num - (num%divisor)

In [2]: round_down(19,10)
Out[2]: 10

In [3]: round_down(19,5)
Out[3]: 15

In [4]: round_down(10,10)
Out[4]: 10
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
2

This probably isn't the most efficient solution, but

def round_down(m, n):
    return m // n * n

is pretty simple.

MisterMiyagi
  • 36,972
  • 7
  • 82
  • 99
1

I ended up doing the following when in the same situation, making use of the floor function. In my case I was trying to round numbers down to nearest 1000.

from math import floor


def round_down(num, divisor):
    return floor(num / divisor) * divisor

Could do a similar thing with ceil if you wanted to define a corresponding always-round-up function as well(?)

TheArchDev
  • 55
  • 5
  • 1
    This works, but involves way more, and more complex operation + import ... then the axepted ansler – d.raev May 04 '19 at 06:20
  • Using ``float`` operations is limited by floating point resolution. For example, this will give wrong results for ``round_down(10000000000000000002001, 1000)``. – MisterMiyagi Nov 12 '21 at 10:56