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

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


当前回答

这是我写的一个angular提供程序,它利用了@profitehlolz的答案,但使用了内存,这样常用的pad长度-pad字符组合就不会不必要地调用数组构建连接:

angular.module('stringUtilities', [])
    .service('stringFunctions', [function() {
        this.padMemo={ };
        this.padLeft=function(inputString,padSize,padCharacter) {

            var memoKey=padSize+""+padCharacter;

            if(!this.padMemo[memoKey]) {

                this.padMemo[memoKey]= new Array(1 + padSize).join(padCharacter);
            }

           var pad=this.padMemo[memoKey];
           return (pad + inputString).slice(-pad.length);
       };
}]);

其他回答

如果你使用Lodash。

Var n = 1; 警报(_。padLeft(n, 2,0));/ / 01 N = 10; 警报(_。padLeft(n, 2,0));/ / 10 < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js " > < /脚本>

我使用

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

哪个前导有4个0

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

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

可变长度填充功能:

function addPaddingZeroes(value, nLength)
{
    var sValue = value + ''; // Converts to string

    if(sValue.length >= nLength)
        return sValue;
    else
    {
        for(var nZero = 0; nZero < nLength; nZero++)
            sValue = "0" + sValue;
        return (sValue).substring(nLength - sValue.length, nLength);
    }
}

如果npm在你的环境中可用,可以使用一些现成的包:www.npmjs.com/browse/keyword/zeropad。

我喜欢零填充。

安装

$ npm install zero-fill

使用

var zeroFill = require('zero-fill')

zeroFill(4, 1)      // '0001' 
zeroFill(4, 1, '#') // '###1' custom padding
zeroFill(4)(1)      // '0001' partials

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

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"