Pad 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:
- Rounding numbers with Javascript (Tuesday, May 5th 2009)
- Pad a number with leading zeroes in Javascript - Improved (Friday, May 1st 2009)
- Format a date time in Javascript in database format (Friday, April 24th 2009)
- Pad a number to two digits with Javascript (Tuesday, April 21st 2009)
- Pad a number with leading zeroes in Javascript (Sunday, April 19th 2009)

Comments
blog comments powered by Disqus