798

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
chris
  • 8,219
  • 4
  • 18
  • 14
  • 174
    I've found [this](http://www.codigomanso.com/en/2010/07/simple-javascript-formatting-zero-padding/) wich I guess is far more simple: `("00" + h).slice (-3);` – Paulo Bueno Jul 30 '12 at 20:26
  • 11
    @PauloBueno `("00" + 1234).slice (-3);` gives `234` i.e. discards the most significant figure. – Daniel Earwicker Aug 14 '12 at 08: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... – Paulo Bueno Aug 15 '12 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 '15 at 14:55
  • To use @loafer solution without knowing in advance the maximum length of your number, you should first use the following: `size = ('' + num).length;` (for positive integer values) – Francisco Alvarado May 20 '16 at 15:53
  • I also like @loafer's approach, but it doesn't work if the number has more digits than the intended size. This seems to work better: `(num/Math.pow(10, size) + '').replace(/0{0,1}\./m, '')`. Keep in mind that both solutions only work for integers. – Julian D. Oct 12 '16 at 11:44
  • 22
    Now javascript supports [padStart](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/padStart): `(5).toString().padStart(3, "0")`. – fdelia Feb 05 '18 at 11:02
  • A simple one-liner using ternary logic: `num < 10 ? num = '0'+num : null` – Lewis Donovan Jan 30 '19 at 14:26
  • 1
    ECMA2017 lets you use `num.toString().padStart(5,'0')` which will pad a number to be of length 5. (ie `33` becomes `00033`) – MattCochrane Jul 04 '19 at 00:51
  • `zeroPad = (num, size) => "0".repeat(size -1) + num;` – berniecc Apr 20 '22 at 11:19

6 Answers6

959

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.

Spectric
  • 30,714
  • 6
  • 20
  • 43
InfinitiesLoop
  • 14,349
  • 3
  • 31
  • 34
  • 148
    Second function; shorter: ```function pad(num, size){ return ('000000000' + num).substr(-size); }``` – Blaise Feb 24 '13 at 12:42
  • 10
    ^ Negative values won't work in many versions of IE. – InfinitiesLoop Feb 24 '13 at 16:45
  • 8
    Ah, apparently slice() works with negative values in IE though :) http://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring-in-javascript – InfinitiesLoop Feb 26 '13 at 06:08
  • Perhaps an example how to call the function and result? – Enrico Aug 09 '13 at 09:20
  • 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 09 '13 at 09:48
  • It's even nicer if you use spaces instead of 0s. – jsejcksn May 26 '16 at 10:29
  • The second function is 5 times faster. http://js.do/code/padding – Whitecat Jul 20 '16 at 05:06
  • ES6: const pad = (n, s) => ('000000000' + n).substr(-s); – Timmerz Feb 08 '17 at 19:31
  • 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 })` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString – jrz Mar 11 '19 at 17:38
  • Uhm, just of curiosity, the first version (with `while (s.length < size) s = "0" + s;`) seems to have quadratic run time (i.e. O(N^2)) - is it something about string concatenation in JS that I don't know, or no one really cares about asymptotic complexity in JS anymore? :) – J0HN Apr 04 '19 at 05:26
  • The first argument preserves the number if it's longer than the padding, and the second will truncate the number. So `pad("123",2)` will give `123` for the first and `23` for the second. – Liggliluff Nov 07 '19 at 11:54
  • Here's a lighter version: `function pad(n, t) { for (n = n.toString(); n.length < t;) n = "0" + n; return n }` – user10398534 Nov 07 '20 at 21:58
  • substr() is considered deprecated, use substring() instead :) – Hannes Schaletzky Mar 22 '23 at 08:26
598

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" :)
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
265

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"
pim
  • 12,019
  • 6
  • 66
  • 69
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • 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 01 '13 at 14:35
  • yeah, it does, it checks the total length and compares that. – Mild Fuzz Aug 01 '13 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 '14 at 10:59
  • `(9).pad()` and `(7).pad(3)` with parens! – trusktr Mar 11 '15 at 00:57
  • @Adam have you seen the date of the article? so this will not perform well in IE6, :scream:! Thanks Mild. – Luis Lopes Oct 28 '16 at 17:23
  • 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 04 '16 at 19:51
  • This answer was written a long time ago, but I would say that I think there is a delightful elegance in extended prototypes. I understand the risks, and I never do this on client work but I do like it. The risk can be mitigated by name spacing, calling it _myPad or something. – Mild Fuzz Nov 05 '16 at 08:40
  • But yeah, if you don't fully understand the risks, do not do this. – Mild Fuzz Nov 05 '16 at 08:41
  • Performance of extended function will be less then simple function. So do not extend prototypes. – acidernt Nov 10 '16 at 09:01
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"
}
Community
  • 1
  • 1
dave1010
  • 15,135
  • 7
  • 67
  • 64
  • 56
    This is good but it has a fatal flaw. For example, `pad (1234, 3) === "234"`! Which is obviously, unacceptable. – Brock Adams Jun 07 '12 at 23:54
  • 4
    It's also broken if you want padding longer than 15. Elegant, but pretty inflexible. – Mild Fuzz Dec 12 '13 at 20:05
  • 1
    @dave1010 I got a bad result `pad(1234)` yields `"1000000000001234"` . with parameter `pad(1234,20)` yields `"1000000000001234"` Thanks @Brock Adams – JamesThomasMoon Feb 26 '15 at 23:54
  • @JamesThomasMoon1979, see [this answer](http://stackoverflow.com/a/1268377/331508). 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. – Brock Adams Feb 27 '15 at 00:54
  • @BrockAdams My test case is in my prior comment. It did not work properly. Tested on firefox 35 on Ubuntu. – JamesThomasMoon Feb 27 '15 at 21:20
15
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Shef
  • 44,808
  • 15
  • 79
  • 90
ithinc
  • 183
  • 1
  • 2
4

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...

Christoph
  • 164,997
  • 36
  • 182
  • 240