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; }
Code language: JavaScript (javascript)

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

toAtleastTwoPlaces(9); //Returns "09" toAtleastTwoPlaces(10); //Returns "10" toAtleastTwoPlaces(999); //Returns "999"
Code language: JavaScript (javascript)

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);
Code language: JavaScript (javascript)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments