我想使用 JavaScript 对整数进行舍入。例如:
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.
Math.round() rounds to the nearest integer. To round to any other digit, divide and multiply by powers of ten.
Math.round()
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.
floor
ceiling
10
20
or this
var i = 20; var yourNumber = (parseInt(i/10, 10)+1)*10;
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