How to output numbers with leading zeros in JavaScript?

JavascriptText FormattingNumber Formatting

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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" :)

Solution 3 - Javascript

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"

Solution 4 - Javascript

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

Solution 5 - Javascript

function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

Solution 6 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchrisView Question on Stackoverflow
Solution 1 - JavascriptInfinitiesLoopView Answer on Stackoverflow
Solution 2 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 3 - JavascriptMild FuzzView Answer on Stackoverflow
Solution 4 - Javascriptdave1010View Answer on Stackoverflow
Solution 5 - JavascriptithincView Answer on Stackoverflow
Solution 6 - JavascriptChristophView Answer on Stackoverflow