3

For example. I want to print numbers from 1 to 20

but I want print 1 as 01 , 2 as 02 and so on ..

5 Answers 5

3
formatNumber = function( num )
{
  if ( num < 10 )
  {
    return "0" + num;
  }
  else
  {
    return "" + num;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Here is shorter version:

leadingZero = function(num){
    return (num < 10) ? "0"+num : num;
}

Comments

3

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"

Comments

2

Let's abuse the ternary operator:

for(var n = 1; n <= 20; n++) {
    console.log((n < 10 ? '0' : '') + n)
}

Comments

1

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'));
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.