0

The case here is

I have numbers from 1 - 999 and I need to prepand the zero if there is not enough for 3 digit

eg.

1 => 001
9=>009
11=> 011
111 =>111

Is there any way to do this kind of task? thanks

user1871516
  • 979
  • 6
  • 14
  • 26

4 Answers4

2
function get3DigitStr(num) {
  if (num > 99) return num + "";
  var s = "00" + num;
  return s.substr(-3);
}
closure
  • 7,412
  • 1
  • 23
  • 23
1

The pad(number,length) function takes a number and the amount of padding to add to it. It then loops n times adding a 0 each time until the length is satisfied.

   function pad(number, length) {
      var str = '' + number;
      while (str.length < length) {
         str = '0' + str;
      }
      return str;
   }

    var results = [];

    for(var i = 0; i < 999; i++){
       results[i] = pad(i,3); 
    }

    console.log(results);
            /* Outputs ["001","002","003","004", "005", "006","007","011","012","013","014","015","111","222", "333"]*/
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Try this :

var value
while ((value+"").length < 3)
    value = "0" + value;
document.write(value);
Sovan
  • 104
  • 3
1

Try this function:

function add(value) {
    return value.length < 3 ? add("0"+value) : value
}

Here's some examples:

var newvalue = add("1"); //newvalue = "001"
var newvalue = add("21"); //newvalue = "021"
var newvalue = add("999"); //newvalue = "999"

You can test it out here: DEMO

Niklas
  • 13,005
  • 23
  • 79
  • 119