tags:

views:

90

answers:

4

Hi, I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats.

My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc.

5 and higher should round up, 4 and lower should round down.

This is the code I have that does this:

round_int(x):
    last_dig = int(str(x)[-1])
    if last_dig >= 5:
        x += 10
    return (x/10) * 10

Is this the best way to achieve what I want to achieve? Is there a built-in function that does this? Additionally, if this is the best way, is there anything wrong with the code that I missed in testing?

+2  A: 

Slightly simpler:

def round_int(x):
    return 10 * ((x + 5) // 10)
cobbal
Hmmm thank you haha. It is simpler
tablo_an
haha rounds UP as requested for x in (-5, -15, -25, ...) which is not what the average punter expects to happen
John Machin
+7  A: 

Actually, you could still use the round function:

>>> print round(1123.456789, -1)
1120.0

This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.

data
O wow I did not know that
tablo_an
A: 

if you want the algebric form and still use round for it it's hard to get simpler than:

interval = 5
n = 4
print(round(n/interval))*interval
ThE_JacO
+1  A: 

round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:

>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000
Mark Tolonen