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

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


当前回答

如果填充数事先知道不超过某个值,还有另一种不循环的方法:

var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

function zeroFill(number, width) {
    // make sure it's a string
    var input = number + "";  
    var prefix = "";
    if (input.charAt(0) === '-') {
        prefix = "-";
        input = input.slice(1);
        --width;
    }
    var fillAmt = Math.max(width - input.length, 0);
    return prefix + fillZeroes.slice(0, fillAmt) + input;
}

测试用例在这里:http://jsfiddle.net/jfriend00/N87mZ/

其他回答

function zeroFill(number, width) {
    width -= (number.toString().length - /\./.test(number));
    if (width > 0) {
        return new Array(width + 1).join('0') + number;
    }
    return number + ""; // always return a string
}

对Peter的代码做了轻微的修改。在他的代码中,如果输入是(1.2,3),返回值应该是01.2,但它返回的是1.2。这里的变化应该会纠正这一点。

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

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'

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

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

仅供参考,更清晰,更可读的语法恕我直言

"use strict";
String.prototype.pad = function( len, c, left ) {
    var s = '',
        c = ( c || ' ' ),
        len = Math.max( len, 0 ) - this.length,
        left = ( left || false );
    while( s.length < len ) { s += c };
    return ( left ? ( s + this ) : ( this + s ) );
}
Number.prototype.pad = function( len, c, left ) {
    return String( this ).pad( len, c, left );
}
Number.prototype.lZpad = function( len ) {
    return this.pad( len, '0', true );
}

这也导致结果的视觉和可读性问题比其他一些解决方案更少,这些解决方案强制'0'作为字符;回答我的问题,我该怎么做,如果我想垫其他字符,或在其他方向(右填充),同时保持容易打字,并清楚地阅读。我敢肯定,这也是DRY的最佳示例,实际的前导零填充函数体的代码最少(因为其他相关函数在很大程度上与这个问题无关)。

该代码可通过github用户的gist进行评论(代码的原始来源) https://gist.github.com/Lewiscowles1986/86ed44f428a376eaa67f

在控制台和脚本测试中注意,数值文字似乎需要括号或变量才能调用方法,因此2.pad(…)将导致错误,而(2).pad(0,'#')不会。这似乎对所有数字都是一样的

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

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

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