0

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
Community
  • 1
  • 1
SOF User
  • 7,590
  • 22
  • 75
  • 121
  • 4
    Eventually this could help ? http://stackoverflow.com/questions/4726040/javascript-adding-zeros-to-the-beginning-of-a-string-max-length-4-chars – evotopid Dec 27 '11 at 18:49
  • You can apply your own logic to format the numbers you're asking. – Lion Dec 27 '11 at 18:51

5 Answers5

4

This is trivial.

var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;

You can make this into a function easily yourself.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1
function pad(number, length) 
{
    var result = number.toString();
    var temp = length - result.length;

    while(temp > 0) 
    {
        result = '0' + result;
        temp--;
    }

    return result;
}
Lion
  • 18,729
  • 22
  • 80
  • 110
0

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.

TheUnexpected
  • 3,077
  • 6
  • 32
  • 62
0

http://jsfiddle.net/K3mwV/

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);
}
Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49
0
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;
}
Raynos
  • 166,823
  • 56
  • 351
  • 396