Javascript:回合100

Ale*_*lex 0 javascript math numbers rounding

我试图围绕一个数字100.

例:

1340 should become 1400
1301 should become 1400
Run Code Online (Sandbox Code Playgroud)

298 should become 300
200 should stay   200
Run Code Online (Sandbox Code Playgroud)

我知道Math.round但它没有圆到100.

我怎样才能做到这一点 ?

Phy*_*sis 19

原始答案

使用该Math.ceil功能,例如:

var result = 100 * Math.ceil(value / 100);
Run Code Online (Sandbox Code Playgroud)

广义版本

该功能可以概括如下:

Number.prototype.roundToNearest = function (multiple, roundingFunction) {
    // Use normal rounding by default
    roundingFunction = roundingFunction || Math.round;

    return roundingFunction(this / multiple) * multiple;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用这个函数如下:

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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