For example. I want to print numbers from 1 to 20
but I want print 1 as 01 , 2 as 02 and so on ..
Here's a generic 'zeroPad' function for you:
function zeroPad(nr,base){
base = base || 10;
var len = (String(base).length - String(nr).length)+1;
return len > 0 ? new Array(len).join('0')+nr : nr;
}
//usage
zeroPad(5); //=> "05"
zeroPad(50,1000); //=> "0050"
zeroPad(50); //=> "50"
or as Number Extension:
Number.prototype.zeroPad = Number.prototype.zeroPad ||
function(base){
base = base || 10;
var len = (String(base).length - String(this).length)+1;
return len > 0 ? new Array(len).join('0')+this : this;
};
//usage
(5).zeroPad(); //=> "05"
(50).zeroPad(1000); //=> "0050"
(50).zeroPad(); //=> "50"
Use String.prototype.padStart:
`${num}`.padStart(2, '0');
From MDN:
The
padStart()method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
padStart is only defined on strings—not numbers—so you need to cast the number to string (num.toString(); or more idiomatically `${num}`) before you call padStart. The first parameter is the minimum length of the outcome string so if you numbers reach the hundreds do `${num}`.padStart(3, '0').
// Create an array of the numbers 1 through 20.
const arr = Array.from({ length: 20 }, (_, i) => i + 1);
arr.forEach(i => {
// Pad each one digit number with a leading zero.
console.log(`${i}`.padStart(2, '0'));
})