/**
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}