在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
还有另一个版本:
function zPad(s,n){
return (new Array(n+1).join('0')+s).substr(-Math.max(n,s.toString().length));
}
其他回答
ES6让这一点变得相当微不足道:
function pad (num, length, countSign = true) {
num = num.toString()
let negative = num.startsWith('-')
let numLength = negative && !countSign ? num.length - 1 : num.length
if (numLength >= length) {
return num
} else if (negative) {
return '-' + '0'.repeat(length - numLength) + num.substr(1)
} else {
return '0'.repeat(length - numLength) + num
}
}
pad(42, 4) === '0042'
pad(12345, 4) === '12345'
pad(-123, 4) === '-100'
pad(-123, 4, false) === '-0100'
这是你能找到的最简单、最直接的解决方案。
function zerofill(number,length) {
var output = number.toString();
while(output.length < length) {
output = '0' + output;
}
return output;
}
function numberPadding(n, p) {
n = n.toString();
var len = p - n.length;
if (len > 0) {
for (var i=0; i < len; i++) {
n = '0' + n;
}
}
return n;
}
我正在使用这个简单的方法
var input = 1000; //input any number
var len = input.toString().length;
for (i = 1; i < input; i++) {
console.log("MyNumber_" + ('000000000000000' + i).slice(-len));
}
我对这个话题的一点贡献(https://gist.github.com/lucasferreira/a881606894dde5568029):
/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
return (+o < 0 ? "-" : "") + n;
};
用法:
fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"
我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)