How to add Leading Zeros to a Number in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Add Leading Zeros to a Number #

To add leading zeros to a number:

  1. Use the String() object to convert the number to a string.
  2. Call the padStart() method to add zeros to the start of the string.
  3. The padStart method will return a new, padded with leading zeros string.
function addLeadingZeros(num, totalLength) { return String(num).padStart(totalLength, '0'); } console.log(addLeadingZeros(3, 2)); // 👉️ "03" console.log(addLeadingZeros(3, 3)); // 👉️ "003" console.log(addLeadingZeros(3, 4)); // 👉️ "0003" console.log(addLeadingZeros(100, 2)); // 👉️ "100" // 👇️ Alternatively, simply use the Addition (+) operator const num = '00' + 3; console.log(num); // 👉️ "003"

We passed the following 2 arguments to the String.padStart method.

  1. the target length for the string - the string gets padded with the pad string up to this length. This also takes into consideration decimal characters or a minus sign.
  2. the pad string - the substring that should be applied to the beginning of the string.

To be able to use the padStart method, we had to convert the number to a string.

If you convert the padded string back to a number, any of the leading zeros will automatically get dropped. This is because 003 === 3. JavaScript doesn't keep insignificant leading zeros around.

If the length of the string exceeds the provided target length, the entire string gets returned from the padStart method.

If you need to handle negative numbers, you need to add an if statement that adds the minus sign after the leading zeros have been added.
function addLeadingZeros(num, totalLength) { if (num < 0) { const withoutMinus = String(num).slice(1); return '-' + withoutMinus.padStart(totalLength, '0'); } return String(num).padStart(totalLength, '0'); } console.log(addLeadingZeros(3, 2)); // 👉️ "03" console.log(addLeadingZeros(-3, 3)); // 👉️ "-003"

We added an if statement to check if a negative number is provided to the function.

Note that we deliberately don't include the minus sign in the target length for the new string.

To handle negative numbers, we just had to strip the minus, add the leading zeros and add the minus to the front of the string.

An alternative and perhaps simpler approach is to use the addition (+) operator.

const positive = '00' + 5; console.log(positive); // 👉️ "005" const negative = '-' + '00' + String(-5).slice(1); console.log(negative); // 👉️ -005

We used the exact same approach to handle negative numbers as we did with the padStart method.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.