Pad a Number with Leading Zeros in JavaScript

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:

  1. First, convert the number to a string.
  2. 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.

JavaScript
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.

JavaScript
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.

JavaScript
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.

JavaScript
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:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp