Pad a number with Javascript by Hans PufalPad a number with Javascript by Hans Pufal

Posted December 3rd, 2009 in Javascript

In the past I've posted three ways to pad a number in Javascript with leading zeros, none of which dealt with negative numbers. Recently Hans Pufal emailed me a suggested alternative which approaches the padding in a different way and also preserves the sign if the number is negative.

Hans Pufal's Javascript pad function

This is copied and pasted verbatim as emailed to me by Hans.

function pad (n, len, padding) {
  var
    sign = '',
    s = n;

  if (typeof n === 'number') {
    sign = n < 0 ? '-' : '';
    s = Math.abs (n).toString ();
  }
 
  if ((len -= s.length) > 0)
    s = Array (len + 1).join (padding || '0') + s;

  return sign + s;
}

Here's a couple of examples, the first padding the number 3 so it contains two digits, and then -3 so it contains two digits:

document.write(pad(3, 2) + "<br />");
document.write(pad(-3, 2) + "<br />");

This would write the following out to the document:

03
-03

Related posts:

Comments

blog comments powered by Disqus