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

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


当前回答

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

其他回答

以下提供了一个快速的解决方案:

函数numberPadLeft(num, max, padder = "0"){ 返回"" == (num += "") ?“”: (dif = Max - num.length, dif > 0 ? 微调电容器。重复(dif < 0 ?0: dif) + num: num) }

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

数学的力量!

X = integer to pad Y =要填充的零的个数

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}

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

"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,'#')不会。这似乎对所有数字都是一样的

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