我正在尝试将数字四舍五入到 100。
示例:
1340 should become 1400
1301 should become 1400
和
298 should become 300
200 should stay 200
我知道Math.round
但它不会四舍五入到 100。
我怎样才能做到这一点?
最佳答案
原始答案
使用Math.ceil
函数,如:
var result = 100 * Math.ceil(value / 100);
<小时/>
通用版本
这个函数可以概括如下:
Number.prototype.roundToNearest = function (multiple, roundingFunction) {
// Use normal rounding by default
roundingFunction = roundingFunction || Math.round;
return roundingFunction(this / multiple) * multiple;
}
然后您可以按如下方式使用此功能:
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
或者使用自定义舍入函数(例如 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
运行代码的示例是 available here .
关于JavaScript:四舍五入 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17405899/