How to add leading zero to single digit number? Javascript add leading zero to single digit number, you can use slice() method to achieve it.

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

Sample code for Javascript add leading zero to single digit number:

<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

Comments

Leave a Reply

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

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.