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

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

+65
javascript
Nov 05 '09 at 22:46
source share
4 answers

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

var number = 33; console.log(Math.round(number / 10) * 10); 

+138
Nov 05 '09 at 22:48
source share
 Math.round(x / 10) * 10 
+20
Nov 05 '09 at 22:49
source share

Where i is int.

To round to the nearest multiple of 10 ie

11 becomes 10
19 becomes 10
21 becomes 20

 parseInt(i / 10, 10) * 10; 



To round to the nearest multiple of 10 ie

11 becomes 20
19 becomes 20
21 becomes 30

 parseInt(i / 10, 10) + 1 * 10; 
+13
May 28 '15 at 18:01
source share

I need something like this, so I wrote a function. I used the function for decimal rounding here , and since I also use it to round integers, I also set it as the answer. In this case, just enter 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; } 
+6
Jan 09 '15 at 13:31 on
source share



All Articles