807

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

10
  • 174
    I've found this wich I guess is far more simple: ("00" + h).slice (-3); Jul 30, 2012 at 20:26
  • 11
    @PauloBueno ("00" + 1234).slice (-3); gives 234 i.e. discards the most significant figure. Aug 14, 2012 at 8:05
  • 18
    @DanielEarwicker sure it does but you should adjust to the ammount of digits you are expecting. ("000" + 1234).slice(-4), ("0000" + 12345).slice(-5) and so on... Aug 15, 2012 at 19:25
  • 3
    If you also want to limit the length of the number you could use this: return (num/Math.pow(10,size)).toFixed(size).split('.')[1];
    – loafer
    Feb 18, 2015 at 14:55
  • 24
    Now javascript supports padStart: (5).toString().padStart(3, "0").
    – fdelia
    Feb 5, 2018 at 11:02

6 Answers 6

961

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
    num = num.toString();
    while (num.length < size) num = "0" + num;
    return num;
}

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
    var s = "000000000" + num;
    return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the - and read it.

13
  • 148
    Second function; shorter: function pad(num, size){ return ('000000000' + num).substr(-size); }
    – Blaise
    Feb 24, 2013 at 12:42
  • 10
    ^ Negative values won't work in many versions of IE. Feb 24, 2013 at 16:45
  • 8
    Ah, apparently slice() works with negative values in IE though :) stackoverflow.com/questions/2243824/… Feb 26, 2013 at 6:08
  • 2
    figured it out: value = pad(value, 18); ==> always returns 18 characters, so if you add 10 zero's size should be 10.
    – Enrico
    Aug 9, 2013 at 9:48
  • 1
    Another option is to convert the number to a string by locale and specify the minimum number of integer digits num.toLocaleString(undefined, { minimumIntegerDigits: size }) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – jrz
    Mar 11, 2019 at 17:38
618

UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:

const zeroPad = (num, places) => String(num).padStart(places, '0')

console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"

Another ES5 approach:

function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
6
  • 1
    You're not taking into account negative array sizes ;) eg zeroPad(1234, 2) -> RangeError: Invalid array length Jun 8, 2010 at 15:59
  • 3
    According to this benchmark, this method is 5 times slower than the accepted solution: gist.github.com/4382935
    – andrewrk
    Dec 26, 2012 at 20:36
  • 2
    I like the code, but it does seem to be slower in Chrome. Interested in seeing results from other browsers: jsperf.com/zero-padding-number-methods Jun 2, 2013 at 17:58
  • 2
    For Node.js this is the best working solution. GJ Oct 9, 2019 at 9:35
  • 1
    If you're slow like me the argument for num in the .padStart call is NOT the length to pad with but the maximum length to pad to. Important distinction. Jul 8, 2021 at 19:10
266

You could extend the Number object:

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

Examples:

(9).pad();  //returns "09"

(7).pad(3);  //returns "007"
9
  • 1
    I think this is just what I need. The argument 'size' refers to the FINAL character count and not the total number of zeros to add, right?
    – novwhisky
    Aug 1, 2013 at 14:35
  • yeah, it does, it checks the total length and compares that.
    – Mild Fuzz
    Aug 1, 2013 at 14:37
  • Yeah, it depends on where you are using it. It is not inherently bad thing, but if used in a space with lots of third party involvement, potentially a risk with overwriting functionality.
    – Mild Fuzz
    Dec 11, 2014 at 10:59
  • (9).pad() and (7).pad(3) with parens!
    – trusktr
    Mar 11, 2015 at 0:57
  • 5
    The problem is not comparable to globals, nor does it have anything to do with IE6. The problem is perpetual. The fact that it was discovered years ago doesn’t make it go away. The problem is that the language itself evolves. Who’s to say your .pad() will work the same way as a native version, should it ever come along? I can’t find my original comment. Hopefully it’s just a bug in Stack Overflow. If it was deleted, that would be a poor reflection of the state of things around here.
    – Adam
    Nov 4, 2016 at 19:51
69

From https://gist.github.com/1180489

function pad(a, b){
  return(1e15 + a + '').slice(-b);
}

With comments:

function pad(
  a, // the number to convert 
  b // number of resulting characters
){
  return (
    1e15 + a + // combine with large number
    "" // convert to string
  ).slice(-b) // cut leading "1"
}
5
  • 57
    This is good but it has a fatal flaw. For example, pad (1234, 3) === "234"! Which is obviously, unacceptable. Jun 7, 2012 at 23:54
  • 4
    It's also broken if you want padding longer than 15. Elegant, but pretty inflexible.
    – Mild Fuzz
    Dec 12, 2013 at 20:05
  • 1
    @dave1010 I got a bad result pad(1234) yields "1000000000001234" . with parameter pad(1234,20) yields "1000000000001234" Thanks @Brock Adams Feb 26, 2015 at 23:54
  • @JamesThomasMoon1979, see this answer. Not only does it work properly (while most other answers fail many test cases), it significantly outperforms the other approaches -- especially if you use the logarithmic variation linked in the comments. Feb 27, 2015 at 0:54
  • @BrockAdams My test case is in my prior comment. It did not work properly. Tested on firefox 35 on Ubuntu. Feb 27, 2015 at 21:20
15
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
3
  • 1
    When you post code select it and click on the {} button so it gets formatted as such.
    – Shef
    Sep 12, 2011 at 12:05
  • 10
    zfill(1234, 3) === "234" Jun 25, 2012 at 19:26
  • function zFill(n,l){return (l>n.toString().length)?((Array(l).join('0')+n).slice(-l)):n;}
    – Atul Gupta
    Sep 17, 2014 at 11:47
5

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

pad.zeros = new Array(5).join('0');
function pad(num, len) {
    var str = String(num),
        diff = len - str.length;
    if(diff <= 0) return str;
    if(diff > pad.zeros.length)
        pad.zeros = new Array(diff + 1).join('0');
    return pad.zeros.substr(0, diff) + str;
}

If the padding count is large and the function is called often enough, it actually outperforms the other methods...

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