Sometimes, we want to output numbers with leading zeroes in our JavaScript programs.
In this article, we’ll look at how to create numbers with leading zeroes with JavaScript.
String.prototype.padStart
The JavaScript string’s padStart
method lets us add characters we want to a string until it reaches a given length.
For instance, we can write:
const padded = (123).toString().padStart(5, '0')
console.log(padded)
We call toString
on the number to convert it to a string.
Then we call padStart
with 5 to pad the string to length 5.
And we pass in '0'
to pad the number with leading 0’s.
Therefore, padded
is '00123'
.
Write Our Own Code
We can also write our own code to pad a number string with leading zeroes.
For instance, we can write:
const zeroPad = (num, places) => {
const numZeroes = places - num.toString().length + 1;
if (numZeroes > 0) {
return Array(+numZeroes).join("0") + num;
}
return num
}
console.log(zeroPad(5, 2))
console.log(zeroPad(5, 4))
console.log(zeroPad(5, 6))
We create the zeroPad
function that takes the num
and places
parameters.
num
has the number we want to pad with leading zeroes.
places
is the number of decimal places that we want to pad to.
In the function, we compute the numZeroes
variable, which is the number of leading zeroes we want to add to make the string the length set by places
.
We compute that by substracting places
with num.toString().length
plus 1.
This subtracts the final number of places with the length of the number string plus 1.
We add 1 so that we create the correct sized array since we want to add zeroes in between the array entries with join
.
Then if numZeroes
is bigger than 0, we return a string with leading zeroes by creating an array, then calling join
with 0 to create the zero string, and then concatenating that with the num
value.
Otherwise, we return num
itself.
So the console log should log:
05
0005
000005
Conclusion
We can pad our JavaScript nuinmber strings with leading zeroes with the padStart
method or write our own code to do so.