Friday, October 12, 2007

Zero Padding in Java Script (To add leading zeros to a number)

Some times you need to add leading zeros to numbers to form a string like '001' instead of '1'. Rather than writing separate functions or block of code to pad one, two or three zeros, I wrote a general javascript function where you can specify how many zeros to pad. I am sharing this simple javascript function here.

function zeroPad(num,count)
{
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}

The parameters are
  • num - The number to be zero padded, this can be a string or number.
  • count - The total length of the string after it is zero padded, this should be a number.
Return value will be a string.

Example:

var number1 = 5;
var count1 = 3;
var result = zeroPad(number1,count1);
alert(result);

This will return you '005'