在JavaScript中,如何根据数字将数字舍入到最接近的100/1000?

Ere*_*555 8 javascript math max rounding roundup

我有一个可以是2位数的数字,如67,24,82或3位数字,如556,955,865或4位数,依此类推.如何根据数字将数字四舍五入到最接近的n + 1位?

例:

roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000
Run Code Online (Sandbox Code Playgroud)

等等.

Nin*_*olz 11

您可以取十的对数并将值取整以获得该值.

function roundup(v) {
    return Math.pow(10, Math.ceil(Math.log10(v)));
}

console.log(roundup(87));   //   100
console.log(roundup(776));  //  1000
console.log(roundup(2333)); // 10000
Run Code Online (Sandbox Code Playgroud)

对于负数,您可以通过将检查结果作为因子或采取负数来保存符号.那么绝对值是必要的,因为对数仅适用于正数.

function roundup(v) {
    return (v >= 0 || -1) * Math.pow(10, 1 + Math.floor(Math.log10(Math.abs(v))));
}

console.log(roundup(87));    //    100
console.log(roundup(-87));   //   -100
console.log(roundup(776));   //   1000
console.log(roundup(-776));  //  -1000
console.log(roundup(2333));  //  10000
console.log(roundup(-2333)); // -10000
Run Code Online (Sandbox Code Playgroud)


Jon*_*lms 7

 const roundup = n => 10 ** ("" + n).length
Run Code Online (Sandbox Code Playgroud)

只需使用字符数.


Cer*_*nce 5

您可以检查数字中有多少位并使用幂:

const roundup = num => 10 ** String(num).length;
console.log(roundup(87));
console.log(roundup(776));
console.log(roundup(2333));
Run Code Online (Sandbox Code Playgroud)