Rounding down integers to nearest multiple
Question:
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.
Answers:
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
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(?)
This probably isn’t the most efficient solution, but
def round_down(m, n):
return m // n * n
is pretty simple.
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.
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
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(?)
This probably isn’t the most efficient solution, but
def round_down(m, n):
return m // n * n
is pretty simple.