In Python, we can round to the nearest 10 easily with the help of the Python round() function. The Python round() function rounds to the nearest whole number, but we can make an adjustment by dividing the input to our function by 10, and then multiplying by 10.
def round_to_nearest_10(x):
return round(x/10)*10
print(round_to_nearest_10(14))
print(round_to_nearest_10(28))
#Output:
10
30
When working with numbers, rounding can be very valuable when trying to get an approximation or general idea of the scale of a number.
Rounding to the nearest 10 using Python is easy. We can define our own function to round a number to the nearest 10 with the help of the Python built-in round() function.
The round() function by default rounds to the nearest whole number. The trick to rounding to the nearest 10 in Python is to divide the input to the round() function by 10, and then multiply the result by 10.
Below is a function which allows you to round to the nearest 10 in Python.
def round_to_nearest_10(x):
return round(x/10)*10
print(round_to_nearest_10(14))
print(round_to_nearest_10(28))
#Output:
10
30
How to Round to the Nearest Multiple of Any Number in Python
We can easily generalize our function from above to round to the nearest multiple of any number in Python. To round to the nearest multiple of any number, we just need to divide the input to the round() function by that number, and then multiply the result by that number.
def round_to_nearest(x, num):
return round(x/num)*num
For example, if we want to round to the nearest hundred, we pass “100” as the second argument to our function.
def round_to_nearest(x, num):
return round(x/num)*num
print(round_to_nearest(60,100))
print(round_to_nearest(121,100))
#Output:
100
100
If we instead wanted to round to the nearest 33, we would pass “33” as the second argument.
def round_to_nearest(x, num):
return round(x/num)*num
print(round_to_nearest(60,33))
print(round_to_nearest(121,33))
#Output:
66
132
Hopefully this article has been useful for you to learn how to round to the nearest 10 in Python.