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

suu*_*iam 1 javascript math

我正在解决一个问题,要求我返回一个舍入为10的指定幂的数字。例如:

1234, specified power = 2 => 1200
1234, specified power = 3 => 1000
Run Code Online (Sandbox Code Playgroud)

我确实找到了解决此功能问题的方法:

const roundToPower = (num, pow) => {
    return Math.round(num / Math.pow(10, pow)) * Math.pow(10,pow)
};
Run Code Online (Sandbox Code Playgroud)

但是,我不确定它如何以及为什么起作用。

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

Mah*_*Ali 5

让我们将上层功能分为三部分

  1. num / Math.pow(10, pow) 将给定数字除以给定的10的幂。例如,pow = 3 num将除以1000
  2. 然后Math.round()在该小数点上使用use 。
  3. 然后再次均衡我们第一步所做的除法,再乘以十的幂 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
Run Code Online (Sandbox Code Playgroud)