Javascript using round to the nearest 10

Javascript

Javascript Problem Overview


I would like to round integers using JavaScript. For example:

10 = 10
11 = 20
19 = 20
24 = 30
25 = 30
29 = 30

Javascript Solutions


Solution 1 - Javascript

This should do it:

Math.ceil(N / 10) * 10;

Where N is one of your numbers.

Solution 2 - Javascript

To round a number to the next greatest multiple of 10, add one to the number before getting the Math.ceil of a division by 10. Multiply the result by ten.

*Math.ceil((n+1)/10)10;

1->10
2->10
3->10
4->10
5->10
6->10
7->10
8->10
9->10
10->20
11->20
12->20
13->20
14->20
15->20
16->20
17->20
18->20
19->20
20->30
21->30
22->30
23->30
24->30
25->30
26->30
27->30
28->30
29->30
30->40
35-> 40
40-> 50
45-> 50
50-> 60
55-> 60
60-> 70
65-> 70
70-> 80
75-> 80
80-> 90
85-> 90
90-> 100
95-> 100
100-> 110

Solution 3 - Javascript

Math.round() rounds to the nearest integer. To round to any other digit, divide and multiply by powers of ten.

One such method is this:

function round(num,pre) {
    if( !pre) pre = 0;
    var pow = Math.pow(10,pre);
    return Math.round(num*pow)/pow;
}

You can make similar functions for floor and ceiling. However, no matter what you do, 10 will never round to 20.

Solution 4 - Javascript

or this

var i = 20;
var yourNumber = (parseInt(i/10, 10)+1)*10;

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
Questionmark denftonView Question on Stackoverflow
Solution 1 - JavascriptalexnView Answer on Stackoverflow
Solution 2 - JavascriptkennebecView Answer on Stackoverflow
Solution 3 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 4 - JavascriptsillyView Answer on Stackoverflow