在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
Use:
function zfill(num, len) {
return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}
这可以处理负数和数字比字段宽度长的情况。和浮点。
其他回答
function zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) }
一个简单优雅的解,n是数字,l是长度。
函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}
这将保持长度,如果它是超过所需的,而不是改变数字。
N = 500; console.log (nFill (n, 5)); console.log (nFill (n, 2)); 函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}
function pad(toPad, padChar, length){
return (String(toPad).length < length)
? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
: toPad;
}
Pad (5,0,6) = 000005
Pad('10', 0,2) = 10 //如果没有必要,不要填充
pad('S', 'O', 2) = SO
…等。
干杯
这就是ES6的解决方案。
函数pad(num, len) { 返回“0”。repeat(len - num. tostring ().length) + num; } 警报(垫(1234 6));
我对这个话题的一点贡献(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"
我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)