问题
I'm trying to round a number the 100.
Example:
1340 should become 1400
1301 should become 1400
and
298 should become 300
200 should stay 200
I know about Math.round
but it doesn't round to the 100.
How can I do that ?
回答1:
Try this...
function roundUp(value) {
return (~~((value + 99) / 100) * 100);
}
That will round up to the next hundred - 101 will return 200.
jsFiddle example - http://jsfiddle.net/johncmolyneux/r8ryd/
Open your console to see the results.
回答2:
Original Answer
Use the Math.ceil
function, such as:
var result = 100 * Math.ceil(value / 100);
Generalised Version
This function can be generalised as follows:
Number.prototype.roundToNearest = function (multiple, roundingFunction) {
// Use normal rounding by default
roundingFunction = roundingFunction || Math.round;
return roundingFunction(this / multiple) * multiple;
}
Then you can use this function as follows:
var value1 = 8.5;
var value2 = 0.1;
console.log(value1.roundToNearest(5)); // Returns 10
console.log(value1.roundToNearest(5, Math.floor)); // Returns 5
console.log(value2.roundToNearest(2, Math.ceil)); // Returns 2
Or with a custom rounding function (such as banker's rounding):
var value1 = 2.5;
var value2 = 7.5;
var bankersRounding = function (value) {
var intVal = Math.floor(value);
var floatVal = value % 1;
if (floatVal !== 0.5) {
return Math.round(value);
} else {
if (intVal % 2 == 0) {
return intVal;
} else {
return intVal + 1;
}
}
}
console.log(value1.roundToNearest(5, bankersRounding)); // Returns 0
console.log(value2.roundToNearest(5, bankersRounding)); // Returns 10
An example of the code running is available here.
来源:https://stackoverflow.com/questions/17405899/javascript-round-by-100