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

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


当前回答

我们的测试是假的,因为我的有个错别字。

zeroPad = function (num, count) {
    return ((num / Math.pow(10, count)) + '').substr(2);
};

Paul的是最快的,但我认为.substr比.slice快,即使它多了一个字符;)

其他回答

简单的数学运算就可以得到一个单行函数:

function zeroFill( number, width ) {
  return Array(width - parseInt(Math.log(number)/Math.LN10) ).join('0') + number;
}

这是假设number是一个不大于width的整数。如果调用例程不能保证,函数将需要进行一些检查:

function zeroFill( number, width ) {
    var n = width - parseInt(Math.log(number)/Math.LN10);
    return (n < 0) ? '' + number : Array(n).join('0') + number;
}

我在这里寻找一个标准,和保罗和约拿单有同样的想法……他们的照片超级可爱,但这里有一个非常可爱的版本:

function zeroPad(n, l, i) {
    return (i = n/Math.pow(10, l))*i > 1 ? '' + n : i.toFixed(l).replace('0.', '');
}

这也可以(我们假设是整数,对吗?)…

> zeroPad(Math.pow(2, 53), 20);
'00009007199254740992'

> zeroPad(-Math.pow(2, 53), 20);
'-00009007199254740992'

> zeroPad(Math.pow(2, 53), 10);
'9007199254740992'

> zeroPad(-Math.pow(2, 53), 10);
'-9007199254740992'

我发现这个问题很有趣,我贡献了自己的一份力量

function zeroLeftComplete(value, totalCharters = 3) { const valueString = value.toString() || '0' const zeroLength = valueString.length - totalCharters if (Math.sign(parseInt(zeroLength)) === -1) { const zeroMissing = Array.from({ length: Math.abs(zeroLength) }, () => '0').join('') return `${zeroMissing}${valueString}` } else return valueString }; console.log(zeroLeftComplete(0)); console.log(zeroLeftComplete(1)); console.log(zeroLeftComplete(50)); console.log(zeroLeftComplete(50561,3));

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

(也适用于负数和小数)

代码:

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'

一个简单优雅的解,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;}