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

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


当前回答

这是我用来填充7个字符的数字。

("0000000" + number).slice(-7)

这种方法可能对大多数人来说已经足够了。

编辑:如果你想让它更通用,你可以这样做:

("0".repeat(padding) + number).slice(-padding)

编辑2:注意,自ES2017以来,你可以使用String.prototype.padStart:

number.toString().padStart(padding, "0")

其他回答

我使用

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

哪个前导有4个0

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

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

function zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) } 

我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:

function zerofill(number, width) {
    var num = '';
    while (width-- > 0) {
        num += '0';
    }

    return num.slice(0, - (number + '').length) + number + '';
}

这个方法不是更快,但它相当原生。

zeroPad = function (num, count) {
    return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};

这就是ES6的解决方案。

函数pad(num, len) { 返回“0”。repeat(len - num. tostring ().length) + num; } 警报(垫(1234 6));