40

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
  • 29,987
  • 31
  • 114
  • 156
  • 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
  • @CristianCiupitu: That's a bad duplicate; there are much cleaner/fully-correct solutions for rounding *down* than for rounding to nearest, so adapting answers to that question to this question would lead to suboptimal solutions. – ShadowRanger Jul 01 '22 at 00:40

3 Answers3

97
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
  • 110,290
  • 27
  • 149
  • 241
5

This probably isn't the most efficient solution, but

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

is pretty simple.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
PrimeNumbers
  • 117
  • 1
  • 8
  • 1
    And unlike using `floor(m / n)`, `m // n` never loses precision and works no matter how big the inputs are (the temporary `float` involved in `m / n` has precision and magnitude limits that `int`s lack). – ShadowRanger Jul 01 '22 at 00:36
0

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
  • 53
  • 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
  • 1
    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