在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?

注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。


当前回答

exports.pad = (num, length) => "0".repeat(length - num.toString().length) + num;

其他回答

我没有看到任何人指出,当你使用String.prototype.substr()与负数时,它从右边计数。

OP问题的一个线性解决方案,即数字5的6位零表示,是:

console.log((“00000000” + 5).substr(-6));

概括起来,我们会得到:

函数pad(num, len) {return ("00000000" + num).substr(-len)}; console.log(垫(5、6)); console.log(垫(45岁,6)); console.log (pad (345 6)); console.log (pad (2345 6)); console.log (pad (12345 6));

还有另一个版本:

function zPad(s,n){
    return (new Array(n+1).join('0')+s).substr(-Math.max(n,s.toString().length));
}

我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作

(也适用于负数和小数)

代码:

function fillZeroes(n = 0, m = 1) {
  const p = Math.max(1, m);
  return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}

输出:

console.log(fillZeroes(6, 2))          // >> '06'
console.log(fillZeroes(1.35, 2))       // >> '01.35'
console.log(fillZeroes(-16, 3))        // >> '-016'
console.log(fillZeroes(-1.456, 3))     // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3))  // >> 'Agent 007'

只是想评论一下(但我没有足够的分数),投票最多的答案是负数和小数

function padNumber(n,pad) {
    p = Math.pow(10,pad);
    a = Math.abs(n);
    g = (n<0);
    return (a < p) ?  ((g ? '-' : '') + (p+a).toString().substring(1)) : n;
}

padNumber( -31.235, 5);

"-00031.235"
function zFill(n,l){
    return 
      (l > n.toString().length) ? 
        ( (Array(l).join('0') + n).slice(-l) ) : n;
}