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

How to round up number to nearest 100/1000 depending on number, in JavaScript?

我有一个号码,可以是 2 位数字,例如 67、24、82,也可以是 3 位数字,例如 556、955、865 或 4 位数字等等。如何根据数字将数字四舍五入到最接近的 n+1 位数字?

示例:

roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000

等等。

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

const roundup = num => 10 ** String(num).length;
console.log(roundup(87));
console.log(roundup(776));
console.log(roundup(2333));

 const roundup = n => 10 ** ("" + n).length

只用字符数。

您可以结合使用 String#repeatNumber#toString 来实现这一点:

const roundUp = number => +('1'+'0'.repeat(number.toString().length));

console.log(roundUp(30));
console.log(roundUp(300));
console.log(roundUp(3000));

你可以取十的对数,然后四舍五入得到这个值。

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

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

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

//Math.pow(10,(value+"").length)   


console.log(Math.pow(10,(525+"").length))
console.log(Math.pow(10,(5255+"").length))

我想到了另一个不需要创建新函数的解决方案