Javascript add leading zero to single digit number

JavaScript

The slice() method returns the value, as a new value. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

<script type="text/javascript">

  var number = 25;
  number = ('0' + number).slice(-2);
  console.log("25 Converted into: "+number);

  number = 5;
  number = ('0' + number).slice(-2);
  console.log("5 Converted into: "+number);

</script>

Output:

25 Converted into: 25
5 Converted into: 05

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *