Pad a number with leading zeroes in Javascript
Posted April 19th, 2009 in Javascript (Updated April 20th, 2009)
As far as I have been able to tell there isn't a built-in way with Javascript to pad a number with leading zeroes to make it a fixed width like with e.g. sprintf in other programming langages. This post looks at a way to pad a number with zeroes with Javascript.
Please note: this doesn't work for negative numbers; it was designed specifically for padding with leading a zeros a number which will be used in date formats where negatives are not possible (there will be a post later this week about this). I'll write another post to revise what's here and will work with negative numbers.
The following function will pad a number with leading zeroes so the resulting string is "length" length. For example if length is 2 and the passed in number is 5 the value returned is 05.
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Some code to test the above:
document.write(pad(1, 1) + '<br />'); document.write(pad(1, 2) + '<br />'); document.write(pad(15, 2) + '<br />'); document.write(pad(1, 3) + '<br />'); document.write(pad(15, 3) + '<br />'); document.write(pad(155, 3) + '<br />'); document.write(pad(1, 4) + '<br />'); document.write(pad(1, 5) + '<br />');
And the resulting output:
1 01 15 001 015 155 0001 00001
On Tuesday I'll look at a second solution if you only ever need to pad a number to two numbers, like you would for days and months, and hours, minutes and seconds.
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)
- Replacing text with Javascript (Tuesday, February 10th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)

Comments
blog comments powered by Disqus