Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round integers to the nearest 10

Tags:

python

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:

def 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?

like image 776
tablo_an Avatar asked Jul 27 '10 23:07

tablo_an


People also ask

How do you round your answer to the nearest 10?

To round the decimal number to its nearest tenth, look at the hundredth number. If that number is greater than 5, add 1 to the tenth value. If it is less than 5, leave the tenth place value as it is, and remove all the numbers present after the tenth's place.


1 Answers

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.

like image 171
data Avatar answered Oct 08 '22 12:10

data