How To Format A Number Into 2 Digit? - Save My Knowledge
Thursday, April 2, 2015

How To Format A Number Into 2 Digit?

There is many people with this issue, to have a 2 digit number, when there is only 1 digit. Example: we just have "2" number, but we need to put 2 digit and the prefix of our number should filled by "0" like "02". How we can do that?

There is a simple answer. We just need 1 line of code to put it right. Let's see the example below:
var myNumber = 7;
newNumber = ("0" + myNumber).slice(-2);
The newNumber variable should be shown as "07", since you have add "0" before it and slice function will reduce it into 2 digit only