0

I do a for loop and would like to get it well aligned.

for(var i=7;i<14; i++){ console.log( i ) }

I get

7
8
9
10
11
12
13

I want

07
08
09
10
11
12
13

Is there a built in way to do that ? Without cascading testing such i.length=1?'0'+i:i;)


For now I use .toPrecision(2) :

5.00
6.00
7.00
8.00
9.00
10.0
11.0
12.0
13.0
14.0

but it is suboptimal as iterations are integers and cannot have ".xx" .

Salman A
  • 262,204
  • 82
  • 430
  • 521
Hugolpz
  • 17,296
  • 26
  • 100
  • 187

5 Answers5

5

You could use Number#toLocaleString with the right options.

var i;
for (i = 7; i < 14; i++) {
    console.log(i.toLocaleString(undefined, { minimumIntegerDigits: 2 }))
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

Concatenate "00" and your number, and use String.slice with a negative number.

for (var i = 7; i < 14; i++) {
  console.log(("00" + i).slice(-2));
}

Sometime in the future you can use String.padStart for such things:

for (var i = 7; i < 14; i++) {
  console.log(i.toString().padStart(2, "0"));
}
Salman A
  • 262,204
  • 82
  • 430
  • 521
2

You could use String.prototype.padStart() and if it's not natively available, you could add its polyfill, see follow:

if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength,padString) {
        targetLength = targetLength>>0; //floor if number or convert non-number to 0;
        padString = String(padString || ' ');
        if (this.length > targetLength) {
            return String(this);
        }
        else {
            targetLength = targetLength-this.length;
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
            }
            return padString.slice(0,targetLength) + String(this);
        }
    };
}

for (var i = 7; i < 14; i++) {
  console.log(new String(i).padStart(2, '0'));
}

I hope it helps you, bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70
1

for(var i = 7; i < 14; i++){
    console.log(prependZero(i));
}

function prependZero(number) {
    if (number < 10 && number >= 0) {
        number = '0' + number;
    }
    
    return number;
}
Toby Mellor
  • 8,093
  • 8
  • 34
  • 58
0

check this code. this is built in function

<script>
    for (var i = 7; i < 14; i++) {
        console.log(i.toString().padStart(2, "0"));
    }
   </script>

output :

07  
08  
09  
10  
11  
12  
13

you can use also slice

 for (var i = 7; i < 14; i++) {
            console.log(("00" + i).slice(-2));
        }

if you use slice and number > 100

for (var i = 99; i < 104; i++) {
        console.log(("00" + i).slice(-3));
    }
Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43