Implementation of zero-filling before the specified length of JS number is insufficient

Implementation of zero-filling before the specified length of JS number is insufficient

Problem description:
        The length of the output number is required to be fixed. For example, if the length is 2 and the number is 1, 01 will be output, that is, if there are not enough digits, 0 will be added before.
Workaround:
Method 1
function fn1(num, length) {
    return (num/Math.pow(10,length)).toFixed(length).substr(2);
}

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

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

The efficiency of the above three methods is as follows:
console.time('time1');
fn1();
console.timeEnd('time1');//chrome return value: time1: 0.126953125ms


console.time('time2');
fn2();
console.timeEnd('time2'); //chrome return value: time2: 0.0810546875ms


console.time('3');
fn3();
console.timeEnd('time3'); //chrome return value: time3: 0ms

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125806&siteId=291194637