How to round an integer up or down to the nearest 10 using Javascript

Javascript

Javascript Problem Overview


Using Javascript, I would like to round a number passed by a user to the nearest 10. For example, if 7 is passed I should return 10, if 33 is passed I should return 30.

Javascript Solutions


Solution 1 - Javascript

Divide the number by 10, round the result and multiply it with 10 again, for example:

  1. 33 / 10 = 3.3
  2. 3.3 rounded = 3
  3. 3 × 10 = 30

console.log(Math.round(prompt('Enter a number', 33) / 10) * 10);

Solution 2 - Javascript

Math.round(x / 10) * 10

Solution 3 - Javascript

Where i is an int.

To round down to the nearest multiple of 10 i.e.

> 11 becomes 10
> 19 becomes 10
> 21 becomes 20

parseInt(i / 10, 10) * 10;

To round up to the nearest multiple of 10 i.e.

> 11 becomes 20
> 19 becomes 20
> 21 becomes 30

parseInt(i / 10, 10) + 1 * 10;	

Solution 4 - Javascript

I needed something similar, so I wrote a function. I used the function for decimal rounding here, and since I also use it for integer rounding, I will set it as the answer here too. In this case, just pass in the number you want to round and then 10, the number you want to round to.

function roundToNearest(numToRound, numToRoundTo) {
    return Math.round(numToRound / numToRoundTo) * numToRoundTo;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbsView Question on Stackoverflow
Solution 1 - JavascriptGumboView Answer on Stackoverflow
Solution 2 - Javascriptuser187291View Answer on Stackoverflow
Solution 3 - JavascriptCMPView Answer on Stackoverflow
Solution 4 - JavascriptcjbarthView Answer on Stackoverflow