我有一个数字,可以是 2 位数字,例如 67、24、82,也可以是 3 位数字,例如 556、955、865 或 4 位数字等。如何根据数字将数字四舍五入到最接近的 n+1 位数字?
例子:
roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000
等等。
我有一个数字,可以是 2 位数字,例如 67、24、82,也可以是 3 位数字,例如 556、955、865 或 4 位数字等。如何根据数字将数字四舍五入到最接近的 n+1 位数字?
例子:
roundup(87) => 100,
roundup(776) => 1000,
roudnup(2333) => 10000
等等。
您可以取十的对数并四舍五入以获得该值。
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
const roundup = n => 10 ** ("" + n).length
只需使用字符数。
您可以检查数字中有多少位并使用幂:
const roundup = num => 10 ** String(num).length;
console.log(roundup(87));
console.log(roundup(776));
console.log(roundup(2333));
您可以String#repeat
结合使用Number#toString
来实现:
const roundUp = number => +('1'+'0'.repeat(number.toString().length));
console.log(roundUp(30));
console.log(roundUp(300));
console.log(roundUp(3000));
//Math.pow(10,(value+"").length)
console.log(Math.pow(10,(525+"").length))
console.log(Math.pow(10,(5255+"").length))
我想出了另一个不需要创建新函数的解决方案