602

How can I pad a value with leading zeroes 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 padding the value I mean it in the database sense of the word (where a 6-digit padded representation of the number 5 would be "000005").

6
  • 2
    This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean? Commented Aug 12, 2009 at 16:38
  • 7
    For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
    – yurisich
    Commented Nov 12, 2014 at 19:27
  • function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
    – Paolo
    Commented Feb 18, 2016 at 23:52
  • @Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
    – Nick F
    Commented Jun 3, 2016 at 10:28
  • 2
    One liner without Math or While loops or libraries? mynum = "0".repeat((n=6-mynum.toString().length)>0?n:0)+mynum; Commented Sep 12, 2018 at 11:17

78 Answers 78

505

I can't believe all the complex answers on here... Just use this:

var zerofilled = ('0000'+n).slice(-4);

let n = 1
var zerofilled = ('0000'+n).slice(-4);
console.log(zerofilled)

12
  • 54
    Good except for negative numbers and numbers longer than 4 digits.
    – wberry
    Commented Sep 19, 2014 at 22:40
  • 27
    @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
    – Seaux
    Commented Sep 21, 2014 at 4:13
  • 22
    @Seaux, you said: "can't believe all the complex answers", and then started explaining yourself the complexity when commented. This means you understand that there are perspectives from which your answer is not perfect. Hence the complexity.
    – Om Shankar
    Commented Aug 8, 2015 at 7:49
  • 5
    @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
    – Seaux
    Commented Aug 10, 2015 at 23:10
  • 14
    I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice! Commented Dec 16, 2016 at 22:12
378

Since ECMAScript 2017 we have padStart:

const padded = (.1 + "").padStart(6, "0");
console.log(`-${padded}`);

Before ECMAScript 2017

With toLocaleString:

var n=-0.1;
var res = n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false});
console.log(res);

1
  • Could also be String(.1).padStart(6, "0"); Commented Nov 8, 2022 at 7:10
346

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
8
  • 103
    This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2) Commented Sep 14, 2012 at 0:22
  • 17
    This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
    – andrewrk
    Commented Dec 26, 2012 at 20:37
  • 45
    This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers. Commented Jun 15, 2013 at 22:20
  • 8
    @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
    – Seaux
    Commented Dec 8, 2013 at 23:15
  • 2
    ("000000" + somenum).substr(-6,6) where the number of zeros and the -6,6 correspond to the pad width. Same idea but slice take one less param; not sure if slice is faster or slower than subtr. Of course my solution isn't needing variable assignment. Commented Mar 4, 2014 at 7:41
119

I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.

This is what I came up with.

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;
}

Then just use it providing a number to zero pad:

> zeroPad(50,4);
"0050"

If the number is larger than the padding, the number will expand beyond the padding:

> zeroPad(51234, 3);
"51234"

Decimals are fine too!

> zeroPad(51.1234, 4);
"0051.1234"

If you don't mind polluting the global namespace you can add it to Number directly:

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;
}

And if you'd rather have decimals take up space in the padding:

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;
}

Cheers!



XDR came up with a logarithmic variation that seems to perform better.

WARNING: This function fails if num equals zero (e.g. 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;
}

Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)

8
  • 9
    This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
    – Senseful
    Commented Jan 2, 2012 at 4:23
  • 13
    +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?! Commented Jun 15, 2013 at 22:39
  • 10
    Performance measure amongst three top answers here: jsperf.com/left-zero-pad
    – tomsmeding
    Commented Feb 21, 2014 at 16:36
  • 4
    I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
    – XDR
    Commented Aug 18, 2014 at 4:30
  • 2
    The original solution is better, logarithmic variation doesn't work if num can be zero...
    – Ondra C.
    Commented Mar 17, 2015 at 10:03
90

Modern browsers now support padStart, you can simply now do:

string.padStart(maxLength, "0");

Example:

string = "14";
maxLength = 5; // maxLength is the max string length, not max # of fills
res = string.padStart(maxLength, "0");
console.log(res); // prints "00014"

number = 14;
maxLength = 5; // maxLength is the max string length, not max # of fills
res = number.toString().padStart(maxLength, "0");
console.log(res); // prints "00014"

0
87

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)

Edit 2: Note that since ES2017 you can use String.prototype.padStart:

number.toString().padStart(padding, "0")
10
  • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example. Commented Jun 15, 2013 at 22:49
  • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
    – Krystian
    Commented Oct 10, 2013 at 11:27
  • 4
    Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
    – chetbox
    Commented Oct 16, 2013 at 11:33
  • 3
    (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
    – Pavel
    Commented Jun 22, 2017 at 16:17
  • 3
    Nice solution the padStart() Commented Aug 30, 2019 at 10:27
33

Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumIntegerDigits: 3,
    useGrouping: false
});

This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.

var amount = 5;

var text = amount.toLocaleString('en-US',
{
    style: 'decimal',
    minimumFractionDigits: 2,
    useGrouping: false
});

This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.

Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.

Complete Example

4
  • Wow, this is a super clean solution and works in node.js.
    – jishi
    Commented Feb 6, 2016 at 22:21
  • 1
    I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
    – bearvarine
    Commented Sep 16, 2017 at 20:47
  • 2
    True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads. Commented Jul 23, 2018 at 21:03
  • this appears to solve the entirely different problem of formatting numbers to a specific number of decimal places (5 becomes 5.00). the question above is seeking a way to zero pad a number (5 becomes 005).
    – grenade
    Commented Apr 11, 2023 at 11:15
21

If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:

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;
}

Test cases here: http://jsfiddle.net/jfriend00/N87mZ/

3
  • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
    – jfriend00
    Commented Jun 16, 2013 at 1:08
  • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example. Commented Jun 16, 2013 at 1:57
  • 1
    @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
    – jfriend00
    Commented Jun 16, 2013 at 3:07
20

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"

2
  • 1
    I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
    – forforf
    Commented May 23, 2012 at 15:30
  • 3
    @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
    – Seaux
    Commented Dec 8, 2013 at 23:17
17

ECMAScript 2017: use padStart or padEnd

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"

More info:

0
16

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;
}
8
  • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number. Commented Aug 12, 2009 at 17:54
  • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript) Commented Aug 12, 2009 at 18:03
  • Or, skip iteration altogether ;) Commented Aug 12, 2009 at 20:05
  • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
    – coderjoe
    Commented Aug 12, 2009 at 20:09
  • 1
    Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
    – broofa
    Commented Sep 24, 2012 at 12:07
14

I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:

(offset + n + '').substr(1);

Where offset is 10^^digits.

E.g., padding to 5 digits, where n = 123:

(1e5 + 123 + '').substr(1); // => 00123

The hexadecimal version of this is slightly more verbose:

(0x100000 + 0x123).toString(16).substr(1); // => 00123

Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.

1
  • Wow. Short and elegant. Commented Feb 4, 2021 at 17:00
13

I really don't know why, but no one did it in the most obvious way. Here it's my implementation.

Function:

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

Prototype:

Number.prototype.zeroPad=function(digits){
    var num=this+"";
    while(num.length < digits){
        num='0'+num;
    }
    return(num);
};

Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.

13

I use this snippet to get a five-digits representation:

(value+100000).toString().slice(-5) // "00123" with value=123
1
  • just what the doctor ordered!!
    – sureshvv
    Commented Jul 7, 2023 at 3:16
12

In all modern browsers you can use

numberStr.padStart(numberLength, "0");

function zeroFill(num, numLength) {
  var numberStr = num.toString();

  return numberStr.padStart(numLength, "0");
}

var numbers = [0, 1, 12, 123, 1234, 12345];

numbers.forEach(
  function(num) {
    var numString = num.toString();
    
    var paddedNum = zeroFill(numString, 5);

    console.log(paddedNum);
  }
);

Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

10

The power of Math!

x = integer to pad
y = number of zeroes to pad

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}
1
  • While it certainly works, and math is extremely reliable, I would have preferred an extremely verbose write n the approach taken here. What function is this? Commented Apr 28, 2021 at 15:55
9

This is the ES6 solution.

function pad(num, len) {
  return '0'.repeat(len - num.toString().length) + num;
}
alert(pad(1234,6));

1
  • 1
    Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
    – ngryman
    Commented Sep 26, 2016 at 21:52
9

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

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

2
  • 2
    Better: var zfill = _.partialRight(_.padStart, '0');
    – yurisich
    Commented Mar 14, 2016 at 18:03
  • 5
    Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
    – Andy
    Commented Oct 14, 2016 at 20:44
9

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

console.log(("00000000" + 5).substr(-6));

Generalizing we'll get:

function pad(num, len) { return ("00000000" + num).substr(-len) };

console.log(pad(5, 6));
console.log(pad(45, 6));
console.log(pad(345, 6));
console.log(pad(2345, 6));
console.log(pad(12345, 6));

0
9

Don't reinvent the wheel; use underscore string:

jsFiddle

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // Yields: '000005'
2
  • What is the overhead? Importing 2000 functions to use one of them? Commented Nov 29, 2022 at 20:49
  • @PeterMortensen yes, depending on the conditions and constraints, that could be a sound decision. However, with proper tree shaking in your build tool you automatically shed the other 1999 unused functions in your release anyway. Commented Nov 30, 2022 at 22:21
8

After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).

I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.

The code I used can be found here: https://gist.github.com/NextToNothing/6325915

Feel free to modify and test the code yourself.

In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.

So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.

Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.

Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.

My function is:

function pad(str, max, padder) {
  padder = typeof padder === "undefined" ? "0" : padder;
  return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
}

You can use my function with, or without, setting the padding variable. So like this:

pad(1, 3); // Returns '001'
// - Or -
pad(1, 3, "x"); // Returns 'xx1'

Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.

So, I would use this code:

function padLeft(str, len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    str = str + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
padLeft(1, 3); // Returns '001'
// - Or -
padLeft(1, 3, "x"); // Returns 'xx1'

You could also use it as a prototype function, by using this code:

Number.prototype.padLeft = function(len, pad) {
    pad = typeof pad === "undefined" ? "0" : pad + "";
    var str = this + "";
    while(str.length < len) {
        str = pad + str;
    }
    return str;
}

// Usage
var num = 1;

num.padLeft(3); // Returns '001'
// - Or -
num.padLeft(3, "x"); // Returns 'xx1'
1
  • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
    – kevinmicke
    Commented Oct 5, 2015 at 19:17
8

First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.

function zPad(n, l, r){
    return(a=String(n).match(/(^-?)(\d*)\.?(\d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
}

so

           zPad(6, 2) === '06'
          zPad(-6, 2) === '-06'
       zPad(600.2, 2) === '600.2'
        zPad(-600, 2) === '-600'
         zPad(6.2, 3) === '006.2'
        zPad(-6.2, 3) === '-006.2'
      zPad(6.2, 3, 0) === '006'
        zPad(6, 2, 3) === '06.000'
    zPad(600.2, 2, 3) === '600.200'
zPad(-600.1499, 2, 3) === '-600.149'
0
7

The latest way to do this is much simpler:

var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})

output: "02"

1
  • 1
    (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
    – le_m
    Commented Mar 18, 2017 at 21:58
5

Just another solution, but I think it's more legible.

function zeroFill(text, size)
{
  while (text.length < size){
    text = "0" + text;
  }

  return text;
}

1
4

This one is less native, but may be the fastest...

zeroPad = function (num, count) {
    var pad = (num + '').length - count;
    while(--pad > -1) {
        num = '0' + num;
    }
    return num;
};
1
  • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
    – nickf
    Commented Sep 6, 2009 at 23:29
4

My solution

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

Usage

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

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

With ES6+ JavaScript:

You can "zerofill a number" with something like the following function:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
function zerofill(nb, minLength) {
    // Convert your number to string.
    let nb2Str = nb.toString()

    // Guess the number of zeroes you will have to write.
    let nbZeroes = Math.max(0, minLength - nb2Str.length)

    // Compute your result.
    return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}

console.log(zerofill(5, 6))    // Displays "000005"

With ES2017+:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')

console.log(zerofill(5, 6))    // Displays "000005"
1
  • Sweet! Esp. ES2017 version is very handy. Commented Nov 4, 2021 at 17:37
3

The simplest, most straight-forward solution you will find.

function zerofill(number,length) {
    var output = number.toString();
    while(output.length < length) {
      output = '0' + output;
    }
    return output;
}
3

Use recursion:

function padZero(s, n) {
    s = s.toString(); // In case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}
2
  • padZero(223, 3) fails with '0223'
    – Serginho
    Commented Oct 18, 2016 at 10:55
  • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
    – lex82
    Commented Oct 18, 2016 at 12:12
2

Some monkeypatching also works

String.prototype.padLeft = function (n, c) {
  if (isNaN(n))
    return null;
  c = c || "0";
  return (new Array(n).join(c).substring(0, this.length-n)) + this; 
};
var paddedValue = "123".padLeft(6); // returns "000123"
var otherPadded = "TEXT".padLeft(8, " "); // returns "    TEXT"
2
  • 1
    -1 monkeypatching the toplevel namespacing in javascript is bad practice. Commented Sep 7, 2009 at 0:37
  • 2
    True for Object and Array objects, but String is not bad
    – Rodrigo
    Commented Sep 11, 2009 at 16:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.