Member-only story
How to Format Numbers by Prepending a 0 to Single-Digit Numbers in JavaScript?
Sometimes, we may want to format our numbers by pretending zeroes before it until it matches a given length.
In this article, we’ll look at how to format numbers by padding a number with leading zeroes until it meets a given length.
Number.prototype.toLocaleString
One way to pad a number with leading zeroes is to use the toLocaleString
method.
It lets us pad a number with leading zeroes until it reaches a minimum length.
For instance, we can write:
const formattedNumber = (2).toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})
console.log(formattedNumber)
To pad the number 2 with leading zeroes until it’s 2 digits long.
minimumIntegerDigits
is set to 2 so that the returned number string will be at least 2 characters long.
useGrouping
set to false
removes any digit grouping separator for the given locale.
Therefore, formattedNumber
is '02'
.
Write Our Own Function
We can also write our own function to pad a number string until it meets the given length.