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.