gkidd
gkidd

Reputation: 199

Incrementing numbers starting from 0000

I have a starting number to work from which is 0000 and increment it by one, i have that done, but the result is 1,2,3 instead of 0001,0002,0003 etc. How can I achieve this?

Thank you

Upvotes: 3

Views: 3854

Answers (2)

vlatko606
vlatko606

Reputation: 1149

for (let i = 0; i <= 9; i++) {
      for (let j = 0; j <= 9; j++) {
         for (let k = 0; k <= 9; k++) {
          for (let l = 0; l <= 9; l++) {

           let yournumber = i.toString() + j.toString() + k.toString() + l.toString();
            console.log(yournumber);

          }
       }
   }
}

Upvotes: 0

Rob W
Rob W

Reputation: 348992

Let n be the number. Then use the String.slice method as follows:

var output = [], n, padded;
for (n=0; n<=9999; n++) {
    padded = ('000'+n).slice(-4); // Prefix three zeros, and get the last 4 chars
    output.push(padded);
}
console.log(output); // ["0000", "0001", ..., "9999"]

Demo: http://jsfiddle.net/qJSBg/

Upvotes: 6

Related Questions