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

输出固定长度字符串

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

原文: https://wsj123.iteye.com/blog/2412696

问题描述:

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

解决方法:

方法1

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

方法2

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

方法3

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

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

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

-=- END -=-