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

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


当前回答

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

其他回答

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

这一种不太本土,但可能是最快的…

zeroPad = function (num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};

我的解决方案

Number.prototype.PadLeft = function (length, digit) {
    var str = '' + this;
    while (str.length < length) {
        str = (digit || '0') + str;
    }
    return str;
};

使用

var a = 567.25;
a.PadLeft(10); // 0000567.25

var b = 567.25;
b.PadLeft(20, '2'); // 22222222222222567.25

我对这个话题的一点贡献(https://gist.github.com/lucasferreira/a881606894dde5568029):

/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
    for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
    return (+o < 0 ? "-" : "") + n;
};

用法:

fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"

我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)

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。这里的变化应该会纠正这一点。