Pad a number with leading zeros in JavaScript

Nate Pet picture Nate Pet · Apr 9, 2012 · Viewed 539k times · Source

In JavaScript, I need to have padding.

For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.

One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.

Is there was a slicker way of doing this?

Answer

Pointy picture Pointy · Apr 9, 2012

Not a lot of "slick" going on so far:

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1 in there.

Example usage:

pad(10, 4);      // 0010
pad(9, 4);       // 0009
pad(123, 4);     // 0123

pad(10, 4, '-'); // --10