Possible Duplicate:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit
How can I format number to 3 digits like..
9 => 009
99 => 099
100 => 100
Possible Duplicate:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit
How can I format number to 3 digits like..
9 => 009
99 => 099
100 => 100
This is trivial.
var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;
You can make this into a function easily yourself.
function pad(number, length)
{
var result = number.toString();
var temp = length - result.length;
while(temp > 0)
{
result = '0' + result;
temp--;
}
return result;
}
Surely you need to convert those numbers in strings, because numbers datatype don't "support" initial zeros.
You can toString() the number, then check his length (NUMLENGTH), if it's less than the total number of digits you need (MAXDIGITS) then prepend MAXDIGITS-NUMLENGTH zeros to the string.
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
for (i=1;i <= 100;i++) {
e = i+'';
alert('0'.repeat(3 - e.length)+i);
}
function padZeros(zeros, n) {
// convert number to string
n = n.toString();
// cache length
var len = n.length;
// if length less then required number of zeros
if (len < zeros) {
// Great a new Array of (zeros required - length of string + 1)
// Then join those elements with the '0' character and add it to the string
n = (new Array(zeros - len + 1)).join('0') + n;
}
return n;
}