Sometimes, we want to add 0 to number if less than 10 in JavaScript.
In this article, we’ll look at how to add 0 to number if less than 10 in JavaScript.
How to add 0 to number if less than 10 in JavaScript?
To add 0 to number if less than 10 in JavaScript, we can call the string padStart method.
For instance, we write
const n1 = (1).toString().padStart(2, "0");
const n2 = (11).toString().padStart(2, "0");
to call padStart with 2 and '0' to prepend '0' to the number convert to a string if it has less than 2 characters.
Therefore, n1 is '01' and n2 is '11'.
Conclusion
To add 0 to number if less than 10 in JavaScript, we can call the string padStart method.