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

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


当前回答

function uint_zerofill(num, width) {
    var pad = ''; num += '';
    for (var i = num.length; i < width; i++)
        pad += '0';
    return pad + num;
}

其他回答

只是为了好玩,这里是我版本的pad函数:

function pad(num, len) {
  return Array(len + 1 - num.toString().length).join('0') + num;
}

它也不会截断比填充长度更长的数字

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

只是另一种解决方案,但我觉得更容易辨认。

函数zeroFill(text, size) { 而(文本。长度< size){ Text = "0" + Text; } 返回文本; }

我使用

Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT) 

哪个前导有4个0

注:这需要谷歌的应用程序脚本实用程序:

https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args

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

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));