In JavaScript, we can round to the nearest 10 easily with the help of the JavaScript Math.round() method. The JavaScript round() method 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. Here is our function below that will do this:
function round_to_nearest_10(num){
return Math.round(num/10)*10;
};
console.log(round_to_nearest_10(14));
console.log(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 JavaScript is easy. We can define our own function to round a number to the nearest 10 with the help of the JavaScript built-in Math.round() method.
The Math.round() method by default rounds to the nearest whole number. The trick to rounding to the nearest 10 in JavaScript is to divide the input to the round() function by 10, and then multiply the result by 10.
Below is a function that allows you to round to the nearest 10 in JavaScript.
function round_to_nearest_10(num){
return Math.round(num/10)*10;
};
How to Round to the Nearest Multiple of Any Number in JavaScript
We can easily generalize our function from above to round to the nearest multiple of any number in JavaScript. To round to the nearest multiple of any number, we just need to divide the input to the Math.round() method by that number, and then multiply the result by that number.
function round_to_nearest(x, num){
return Math.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.
function round_to_nearest(x, num){
return Math.round(x/num)*num;
};
console.log(round_to_nearest(60,100));
console.log(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.
function round_to_nearest(x, num){
return Math.round(x/num)*num;
};
print(round_to_nearest(60,33))
print(round_to_nearest(121,33))
#Output:
66
132
Hopefully this article has been helpful for you to learn how to in JavaScript round to the nearest 10.