How to Pad a number with Leading Zeros in JavaScript

The padStart() method adds another string to the beginning of the current string (multiple times, if necessary) until the resulting string reaches the given length.

Pad a number with Leading Zeros in JavaScript

To pad leading zeros to a number:

  1. To pad a string with leading zeros, use the padStart() method.
  2. The padstart() method will add zeros to the start of the string until it reaches the specified target length.
    Example –
function padWithZero(num, targetLength) {
  return String(num).padStart(targetLength, '0');
}

const num = 5;

// pad number with 2 leading zeros
console.log(padWithZero(num, String(num).length + 2)); 

// pad number with 3 leading zeros
console.log(padWithZero(num, String(num).length + 3)); 

// pad number with 4 leading zeros
console.log(padWithZero(num, String(num).length + 4));
Pad a number with leading zeros.
Pad a number with leading zeros.

Explanation –
We created a function padWithZero() that can be used to pad a number with leading zeros.

To pad the start of a string, pass two parameters to the padStart method:

  1. The target length is the desired length of the string that the padStart method should return. This method will add padding to the start of the string until the desired length is reached.
  2. To pad a string with another string, we supply the string we want to pad our existing string with as the pad string argument.

If you have a string of length 2 and want to increase the string to a target length of 4, then you need to add 2 leading zeros to the string.

console.log(String(22).padStart(4, '0'));
Pad string with two leading zeros.
Pad string with two leading zeros.

The padStart method returns a string. If you convert the result back to a number, the leading zeros will be dropped.


function padWithZero(num, targetLength) {
  return String(num).padStart(targetLength, '0')
}

console.log(Number(padWithZero(5, 10)));
The leading zeros would be dropped.
The leading zeros would be dropped.