Sometimes, we want to prepend a zero in front of any number below 10 in JavaScript.
In this article, we’ll look at how to prepend a zero in front of any number below 10 in JavaScript.
How to prepend a zero in front of any number below 10 in JavaScript?
To prepend a zero in front of any number below 10 in JavaScript, we can use the JavaScript string’s padStart method.
For instance, we write:
const m = (5).toString().padStart(2, '0')
const n = (100).toString().padStart(2, '0')
console.log(m, n)
to convert 5 to a string with toString and then call padStart to pad the string to length 2 by prepending '0' onto it.
Then we assign the returned string to m.
Likewise, we try to the same thing with 100.
As a result, we see '05' and '100' logged.
Conclusion
To prepend a zero in front of any number below 10 in JavaScript, we can use the JavaScript string’s padStart method.