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

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


当前回答

事实上,我最近不得不想出一些类似的东西。 我想肯定有一种不用循环的方法。

这是我想到的。

function zeroPad(num, numZeros) {
    var n = Math.abs(num);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( num < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

然后使用它提供一个数字到零pad:

> zeroPad(50,4);
"0050"

如果该数字大于填充,则该数字将扩展到填充之外:

> zeroPad(51234, 3);
"51234"

小数也可以!

> zeroPad(51.1234, 4);
"0051.1234"

如果你不介意污染全局命名空间,你可以直接将它添加到Number:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

如果你想让小数在填充中占据空间:

Number.prototype.leftZeroPad = function(numZeros) {
    var n = Math.abs(this);
    var zeros = Math.max(0, numZeros - n.toString().length );
    var zeroString = Math.pow(10,zeros).toString().substr(1);
    if( this < 0 ) {
        zeroString = '-' + zeroString;
    }

    return zeroString+n;
}

干杯!



XDR提出了一个对数变化,似乎表现更好。

警告:如果num = 0(例如zeropad(0,2)),该函数将失败。

function zeroPad (num, numZeros) {
    var an = Math.abs (num);
    var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
    if (digitCount >= numZeros) {
        return num;
    }
    var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
    return num < 0 ? '-' + zeroString + an : zeroString + an;
}

说到性能,tomsmeding比较了前3个答案(4与对数变化)。猜猜哪一个的表现比另外两个好?:)

其他回答

只是另一种解决方案,但我觉得更容易辨认。

函数zeroFill(text, size) { 而(文本。长度< size){ Text = "0" + Text; } 返回文本; }

我用ECMAScript 6 (TypeScript)写了一些东西,也许有人可以使用它:

class Helper {
    /**
     * adds leading 0 and returns string if value is not minSize long,
     * else returns value as string
     *
     * @param {string|number} value
     * @param {number} minSize
     * @returns {string}
     */
    public static leadingNullString(value: string|number, minSize: number): string {
        if (typeof value == "number") {
            value = "" + value;
        }
        let outString: string = '';
        let counter: number = minSize - value.length;
        if (counter > 0) {
            for (let i = 0; i < counter; i++) {
                outString += '0';
            }
        }
        return (outString + value);
    }
}

帮手。leadingNullString (123 2);返回" 123 "

帮手。leadingNullString (5,2);返回“05”

Helper.leadingNullString(40岁,2);返回“40”

ecmaScript4 (JavaScript)编译如下:

var Helper = (function () {
    function Helper() {
    }
    Helper.leadingNullString = function (value, minSize) {
        if (typeof value == "number") {
            value = "" + value;
        }
        var outString = '';
        var counter = minSize - value.length;
        if (counter > 0) {
            for (var i = 0; i < counter; i++) {
                outString += '0';
            }
        }
        return (outString + value);
    };
    return Helper;
}());

我在写一个数字基础转换器时,想到了一个荒谬的单行程序。

//这是被诅咒的 函数p (i, w、z) {z z = | | 0; w = w | | 8; i + = "; var o w = i.length %;还啊?[…数组(言).fill (z),……我]. join():我;} console.log (p (8675309));//默认:pad w/ 0到8位 console.log (p(525600年,10));//输入10个数字 console.log(p(69420, 10, 'X'));// Pad w/ X到10位 console.log (p (8675309, 4));//输入4位数字 console.log (p (12345678));//没必要就别拍

或者,以一种不那么容易暴露我把灵魂出卖给黑Perl的形式:

function pad(input, width, zero) {
    zero = zero || 0; width = width || 8;  // Defaults
    input += '';                           // Convert input to string first

    var overflow = input.length % width    // Do we overflow?
    if (overflow) {                        // Yep!  Let's pad it...
        var needed = width - overflow;     // ...to the next boundary...
        var zeroes = Array(needed);        // ...with an array...
        zeroes = zeroes.fill(zero);        // ...full of our zero character...
        var output = [...zeroes,...input]; // ...and concat those zeroes to input...
        output = output.join('');          // ...and finally stringify.
    } else {
        var output = input;                // We don't overflow; no action needed :)
    }

    return output;                         // Done!
}

这个答案与其他答案不同的一点是,它取数字长度对目标宽度的模,而不是简单的大于检查。如果你想确保结果长度是目标宽度的倍数(例如,你需要输出5或10个字符长),这是很方便的。

我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!

我发现这个问题很有趣,我贡献了自己的一份力量

function zeroLeftComplete(value, totalCharters = 3) { const valueString = value.toString() || '0' const zeroLength = valueString.length - totalCharters if (Math.sign(parseInt(zeroLength)) === -1) { const zeroMissing = Array.from({ length: Math.abs(zeroLength) }, () => '0').join('') return `${zeroMissing}${valueString}` } else return valueString }; console.log(zeroLeftComplete(0)); console.log(zeroLeftComplete(1)); console.log(zeroLeftComplete(50)); console.log(zeroLeftComplete(50561,3));

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