How to Format Numbers by Prepending 0 to Single-Digit Numbers in Javascript

  • Home /
  • Blog Posts /
  • How to Format Numbers by Prepending 0 to single-digit numbers in Javascript

If you have a single-digit number, and you need to format it to always have at-least two digits, then you can use the below function to solve your problem:

function toAtleastTwoPlaces(n){
    return n > 9 ? "" + n: "0" + n;
}

When testing the above method, you could do the following:

toAtleastTwoPlaces(9);   //Returns "09"
toAtleastTwoPlaces(10);  //Returns "10"
toAtleastTwoPlaces(999); //Returns "999"

This is especially useful where you need to format dates:

// INPUT: yyyy-m-d
// OUTPUT: yyyy-mm-dd 

var date = obj.year + "-" + toAtleastTwoPlaces(obj.month) + "-" + toA
tleastTwoPlaces(obj.day);