Reputation: 333
I know that I can round to the closest multiple of 10 in python by using round(<int>, -1)
Is there a way to do this without using this built in function?
Edit:
Thanks for the feedback! The answer using divmod() was interesting because I had never used divmod before. Just in case anyone wants to know on CodingBat the solution used modulo as was suggested in the comments. Here it is in case anyone is interested.
def round10(num):
mod = num % 10
num -= mod
if mod >= 5: num += 10
return num
Upvotes: 1
Views: 3897
Reputation: 521
I have a function that rounds n
to the nearest multiple of d
:
def cm(n,d,o="+"):
p = d - (n % d)
m = n % d
nm = n - m
np = n + p
if p > m:
return nm
elif m > p:
return np
else:
if o == "+":
return np
else:
return nm
How to use: use cm(number, near multiple wanted, preferred direction in special cases)
Examples:
cm(8,10) = 10
cm(6,4,"-") = 4 #special case (n % d == d - n % d)
cm(6,4,"+") = 8 #special case
cm(6,4) = 8
Upvotes: 0
Reputation: 309891
divide by 10
, int
, multiply by 10
.
Actually, you can do it without any builtins using the //
operator:
>>> def round(x):
... return (x//10)*10
...
>>> round(15.)
10.0
>>> round(25.)
20.0
Of course, this always rounds down. If you want to round up for values with a remainder greater than 5, you could use divmod
:
def round(x):
n, remainder = divmod(x, 10)
if remainder >= 5:
n += 1
return n * 10
Upvotes: 2
Reputation: 9077
Round down to the closest multiple of 10:
int(n / 10) * 10
Round up to the closest multiple of 10:
int((n + 10) / 10) * 10
Round to the closest multiple of ten:
(int(n / 10) + bool(n % 10 >= 5)) * 10
Upvotes: 0
Reputation: 76909
This rounds to the closest, not always up or always down:
def xround(n):
return (n + 5) // 10 * 10
Upvotes: 2