我正在解决一个问题,要求我返回一个舍入为10的指定幂的数字。例如:
1234, specified power = 2 => 1200
1234, specified power = 3 => 1000
我确实找到了解决此功能问题的方法:
const roundToPower = (num, pow) => {
return Math.round(num / Math.pow(10, pow)) * Math.pow(10,pow)
};
但是,我不确定它的工作方式和原因。
有人可以为我分解吗?谢谢!
答案 0 :(得分:5)
让上层功能分为三个部分
num / Math.pow(10, pow)
将给定数字除以给定的10的幂。例如pow = 3
num
除以1000
Math.round()
。 Math.pow(10,pow)
的幂再次乘以对于pow = 3
和num = 1230
=> Math.round(1230 / Math.pow(10, 3)) * Math.pow(10, 3)
=> Math.round(1230 / 1000 )) * 1000
=> Math.round( 1.230 )) * 1000
=> 1 * 1000
=> 1000
答案 1 :(得分:1)
我知道问题不在于如何将数字转换为10的指定幂。我知道一种更好,更简单的方法。也许可以帮上忙。
let a = 1234;
a = convert(a,2);
console.log(a); // 1200
let b = 123456;
b = convert(b,5);
console.log(b); //123460
function convert(num, power){
if(power < String(num).length){
num = num.toPrecision(power);
num = Number(num).toFixed();
return num;
}
else{
console.log("Invalid power for number: " + num);
}
}