How to Format Numbers by Prepending 0 to single-digit numbers in Javascript

0 min read 91 words

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);
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags