Pad a JavaScript Number
POSTED AT 17:51 on 4th November 2007
Sometimes when working with numbers in JavaScript you will want to pad a number out to ensure it has any leading zeros required (for currency and dates etc). Here’s a simple bit of code that does just that:
- function pad(number, length){
- var str = "" + number;
- while(str.length<length){
- str = ’0′+str;
- }
- return str;
- }
Simply call the function with your number and the length it needs padding to.



Matt
The code on this page is completely mangled and non functional.
Posted at 03:08 on 18th June 2008
Jacob Wyke
Hi Matt,
Thanks for letting me know. I recently upgraded my server and a lot of my data got damaged in the process.
Posted at 13:16 on 29th July 2008
David
I tested it. It is working.
Posted at 19:16 on 12th November 2009