JS数字指定长度不足前补零的实现

时间:2023-03-09 18:38:15
JS数字指定长度不足前补零的实现

问题描述:
        要求输出的数字长度是固定的,如长度为2,数字为1,则输出01,即不够位数就在之前补足0。

解决方法:

方法1

  1. function fn1(num, length) {
  2. return (num/Math.pow(10,length)).toFixed(length).substr(2);
  3. }

方法2

  1. function fn2(num, length) {
  2. return ( "0000000000000000" + num ).substr( -length );
  3. }

方法3

  1. function fn3(num, length) {
  2. return (Array(length).join('0') + num).slice(-length);
  3. }

上述三种方法的效率如下:

  1. console.time('time1');
  2. fn1();
  3. console.timeEnd('time1');//chrome返回值:time1: 0.126953125ms
  1. console.time('time2');
  2. fn2();
  3. console.timeEnd('time2'); //chrome返回值:time2: 0.0810546875ms
    1. console.time('3');
    2. fn3();
    3. console.timeEnd('time3'); //chrome返回值:time3: 0ms