JS:将数字返回指定的10的幂

时间:2019-11-17 08:33:23

标签: javascript math

我正在解决一个问题,要求我返回一个舍入为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)
};

但是,我不确定它的工作方式和原因。

有人可以为我分解吗?谢谢!

2 个答案:

答案 0 :(得分:5)

让上层功能分为三个部分

  1. num / Math.pow(10, pow)将给定数字除以给定的10的幂。例如pow = 3 num除以1000
  2. 然后在该小数点上使用use Math.round()
  3. 然后再次均衡我们第一步所做的除法,以10 Math.pow(10,pow)的幂再次乘以

示例

对于pow = 3num = 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);
  }
}