I would like to round integers using JavaScript. For example:
10 = 10
11 = 20
19 = 20
24 = 30
25 = 30
29 = 30
Join Stack Overflow to learn, share knowledge, and build your career.
I would like to round integers using JavaScript. For example:
10 = 10
11 = 20
19 = 20
24 = 30
25 = 30
29 = 30
This should do it:
Math.ceil(N / 10) * 10;
Where N is one of your numbers. However, this does not work for your first case (10 rounds to 20, but why would it?).
Math.ceil(10 / 10) * 10 = 10
)
– NayoR
Jan 15 '20 at 14:11
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
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
.
or this
var i = 20;
var yourNumber = (parseInt(i/10, 10)+1)*10;
10
possibly round up to20
? 15, yes; 14 and below would round to10
. – David says reinstate Monica Jun 13 '12 at 20:04