0

我正在尝试将数字四舍五入到 100。

例子:

1340 should become 1400
1301 should become 1400

298 should become 300
200 should stay   200

我知道,Math.round但它没有四舍五入到 100。

我怎样才能做到这一点 ?

4

2 回答 2

22

原始答案

使用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

或者使用自定义舍入功能(例如银行家的舍入):

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

此处提供了运行代码的示例。

于 2013-07-01T13:43:08.200 回答
4

尝试这个...

function roundUp(value) {
    return (~~((value + 99) / 100) * 100);
}

这将四舍五入到下一个百 - 101 将返回 200。

jsFiddle 示例 - http://jsfiddle.net/johncmolyneux/r8ryd/

打开控制台查看结果。

于 2013-07-01T13:43:24.607 回答