In this article, we will learn how to pad a number with leading zeros in JavaScript using the padStart()
method.
To pad a number with leading zeros in JavaScript:
- First, convert the number to a string.
- Then, use the
padStart()
method to add the leading zeros to the number.
The padstart()
method adds leading zeros to the start of the string until it reaches the specified target length.
function padZero(num, targetLength) {
return String(num).padStart(targetLength, '0');
}
const num = 1;
// ποΈ pad with 2 zeros
console.log(padZero(num, 2)); // ποΈ 01
// ποΈ pad with 3 zeros
console.log(padZero(num, 3)); // ποΈ 001
We created a reusable function padZero()
that accepts a number and the target length for adding leading zeros to the number.
Since the padStart()
method only works with string, we converted the number to a string.
The padStart()
method adds a leading zero until it reaches to specified target length.
For example, If you have a string of length 3
and specify a target length of 5
, then 2
leading zeros will get added to the string and if the target length(3
) is equal to the string’s length the string will not get padded.
console.log("111".padStart(5, '0')); // ποΈ 00111
console.log("111".padStart(3, '0')); // ποΈ 111
If you want to add a leading zero regardless of the stringβs length, you need to add the stringβs length to the target length.
function alwaysPadZero(num, targetLength) {
targetLength = targetLength + String(num).length;
return String(num).padStart(targetLength, '0');
}
const num = 111;
// ποΈ pad with 2 zeros
console.log(alwaysPadZero(num, 2)); // ποΈ 00111
// ποΈ pad with 3 zeros
console.log(alwaysPadZero(num, 3)); // ποΈ 000111
We created a reusable function in the function we added the stringβs length to the specified target length. Then we passed the updated target length to the padStart
method. So it will always pad a number with a leading zero.
Note that the padStart()
method returns a string. If you convert the result back to a number, the leading zeros will get removed.
function padZero(num, targetLength) {
return String(num).padStart(targetLength, '0')
}
console.log(Number(padZero(1, 3))); // ποΈ 5
Conclusion
You can use the padStart()
method, to add leading zeros to the number in JavaScript. And note that the padStart()
method returns the number as a string.
Learn More:
- Unexpected identifier Error in JavaScript
- Dynamically Access Object Property Using Variable in JavaScript
- Check if a Key exists in an Object in JavaScript
- Replace All String Occurrences in JavaScript
- Get the Last N Elements of an Array in JavaScript
- Calculate Percentage Between Two Numbers in JavaScript
- Remove Special Characters from a String in JavaScript
- Using async/await with a forEach loop
- Wait for all promises to resolve in JavaScript