How can I pad a value with leading zeros?

2018-12-30 23:59发布

What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?

Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").

30条回答
只靠听说
2楼-- · 2018-12-31 00:41

Here's what I used to pad a number up to 7 characters.

("0000000" + number).slice(-7)

This approach will probably suffice for most people.

Edit: If you want to make it more generic you can do this:

("0".repeat(padding) + number).slice(-padding)
查看更多
牵手、夕阳
3楼-- · 2018-12-31 00:43

Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!

function zerofill(number, length) {
    // Setup
    var result = number.toString();
    var pad = length - result.length;

    while(pad > 0) {
        result = '0' + result;
        pad--;
    }

    return result;
}
查看更多
永恒的永恒
4楼-- · 2018-12-31 00:44

In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):

string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills
查看更多
皆成旧梦
5楼-- · 2018-12-31 00:44

Not that this question needs more answers, but I thought I would add the simple lodash version of this.

_.padLeft(number, 6, '0')

查看更多
皆成旧梦
6楼-- · 2018-12-31 00:45

Simple way. You could add string multiplication for the pad and turn it into a function.

var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);

As a function,

function paddy(num, padlen, padchar) {
    var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
    var pad = new Array(1 + padlen).join(pad_char);
    return (pad + num).slice(-pad.length);
}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2
查看更多
永恒的永恒
7楼-- · 2018-12-31 00:45

The quick and dirty way:

y = (new Array(count + 1 - x.toString().length)).join('0') + x;

For x = 5 and count = 6 you'll have y = "000005"

查看更多
登录 后发表回答