'Javascript using round to the nearest 10 [duplicate]
I would like to round integers using JavaScript. For example:
10 = 10
11 = 20
19 = 20
24 = 30
25 = 30
29 = 30
Solution 1:[1]
This should do it:
Math.ceil(N / 10) * 10;
Where N is one of your numbers.
Solution 2:[2]
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:[3]
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:[4]
or this
var i = 20;
var yourNumber = (parseInt(i/10, 10)+1)*10;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | noamyg |
| Solution 2 | kennebec |
| Solution 3 | trincot |
| Solution 4 |
