是否有一种方法将前导零前置到数字,从而产生固定长度的字符串?例如,如果我指定2个位置,5就变成了“05”。
当前回答
更新:使用ES2017 String.prototype.padStart方法的小一行函数:
const zeroPad = (num, places) => String(num).padStart(places, '0') console.log(zeroPad(5, 2));"05" console.log(zeroPad(5, 4));"0005" console.log(zeroPad(5, 6));"000005" console.log(zeroPad(1234, 2));"1234"
另一种ES5方法:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
其他回答
从https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
评论:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
注意:可能过时了。ECMAScript 2017包含String.prototype.padStart。
您必须将数字转换为字符串,因为数字前导为零是没有意义的。就像这样:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
或者,如果你知道你永远不会使用超过X个0,这可能会更好。这里假设您永远不需要超过10个数字。
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
如果你关心负数,你就得把它剥下来读一读。
你可以扩展Number对象:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
例子:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
更新:使用ES2017 String.prototype.padStart方法的小一行函数:
const zeroPad = (num, places) => String(num).padStart(places, '0') console.log(zeroPad(5, 2));"05" console.log(zeroPad(5, 4));"0005" console.log(zeroPad(5, 6));"000005" console.log(zeroPad(1234, 2));"1234"
另一种ES5方法:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}