How to add leading zeros to a number in JavaScript?

In this tutorial, we’re going to be looking at the different ways to add leading zeros to a number in JavaScript.

Sometimes, your program might require your numbers to have a set number of digits. Other times, you might be required to add a set number of leading zeros to fulfil a purpose.

In those cases, the methods described in this tutorial would be useful to you. Let’s look at them now.

Convert the number to a string

You just can’t print a number with leading zeros. Look at the following example:

console.log(000123); //123 

See how the leading zeros were removed while printing them? As far as your browser is concerned, leading zeros provide no value to a number, and hence it’ll remove them.

So, the only way to retain these 0s while printing is by converting the number to a string first, and then adding the leading 0s to it.

So, let’s look at how to convert a number to a string first. There are many ways to do the same, and we’ll be looking at 3 main methods right now.

Using the toString method

The toString() method is one of the most popular ‘number to string’ conversion methods. Tag the number with the toString() method, as shown below, and you’re good to go.

let num = 5; 
num = num.toString();
console.log(typeof num); //string 

Using the String object

Alternatively, you can also use the String method and send the number as its argument to achieve the same, as shown below:

num = String(num); 

Add an empty string to the number

Any time you add a number to a string, you’ll end up with a string. So, why don’t you add an empty string to your number, and successfully convert it to a string while keeping the value intact?

num = num + ''; 

Use the padStart method to add leading zeros to the number

Now that we’ve converted our number to a string, we can start adding our leading zeros to it. We’ll be looking at 2 methods of doing the same using the padStart method in this section.

As the name implies, the ‘padStart’ method is used to pad the start of the string with the character we require. In our case, we’ll be padding our number (in string format) with 0s.

Add leading zeros when the number of zeros is given

Sometimes, you’ll be given a set number of leading zeros to add to your number. In that case, we can use the following method:

1. Convert the number to a string using the toString() method first.
2. Then, find the total length of the string you need, as in add the current length (the number of digits in your number) to the number of 0s you want to pad to this number.
3. Then, use the padStart method. This method asks for 2 arguments: the length of the final string (after padding) and the character you want to pad the string with, which is ‘0’ in our case. Make sure to send ‘0’ in string format, or this won’t work.

Look at the final code block below:

function leadingZeroes(num, padNum) {
  num = num.toString();
  let length = num.length + padNum;
  return num.padStart(length, '0');
}

console.log(leadingZeroes(12,2)); //0012 

As you can see above, our number was converted to a string, and 2 0s were padding at its start, just like we wanted.

Pad the number with required zeroes until it reaches the given length

In some cases, your program might require a set number of digits. This might be the case in dates (09 instead of 9), for example.

In those cases, our solution becomes quite straightforward. Use the ‘length’ value directly in your ‘padStart’ method, as shown below:

function leadingZeroes(num, length) {
  return num.toString().padStart(length, '0');
}

console.log(leadingZeroes(12,4)); //0012 

Using more string methods

Now that we know we need to convert our number to a string to pad it, and there’s no other way to go about it, why don’t we try to combine the various string methods we have available to us to achieve our purpose?

Manually appending the string with a loop and string concatenation

One of the easiest ways of padding is by using a loop, either a ‘for’ or ‘while’ loop. The padNum values represents the number of 0s you want to pad the number with.

Loop through the ‘padNum’ value, and for every iteration of the loop, concatenate ‘0’ with the current value of ‘num’ by using the ‘+’ operator (you can use the concat operator instead as well).

]function leadingZeroes(num, padNum) {
  for(let i = 0; i < padNum; i++) {
      num = '0' + num;
  }
  return num;
} 

Use string repeat

Instead of using loops and concatenating ‘0’ for every iteration, we can use the repeat() method to create a new string with the required number of 0’s and concatenate that to our number.

We don’t have to use the toString() method in this case because adding a string with a number will always produce a string, as shown below:

function leadingZeroes(num, padNum) {
  return '0'.repeat(padNum) + num;
} 

Using slice with negative indices

The slice method, as the name implies, is a pre-defined string method that’s used to slice a portion of a string.

It creates a copy with the sliced portion (doesn’t affect the original string), which can be used separately or re-assigned to the original string to change its previous value.

If you give 1 as the argument to this method, your browser will slice from the 2nd character (present in the 1st index) till the end of the string.

But, if you give negative values as the argument, it’ll start slicing from the end of the string. -1 will slice just the last character, -2 will slice the last 2 characters, and so on.

In our example, we’ve created a function where we’ve sent the number and the required length (number of digits) as arguments.

To start with, let’s create a string of 0’s of length ‘length’ and concatenate that with the given number.

Finally, let’s slice -length, which will slice the last ‘length’ number of characters (digits), as we needed.

function leadingZeroes(num, length) {
  return ('0'.repeat(length) + num).slice(-length);
} 
console.log(leadingZeroes(12,4)); //0012 

As you can see above, our number is 12, and we need a total of 4 digits in our number. This means we need to pad the first 2 positions with 0s, to create the number 0012.

When we first repeat ‘0’ 4 times (length’s value), we get ‘0000’. Next, let’s concatenate that with num, which will give us ‘000012’.

Finally, let’s slice the last ‘length’ digits from this string, which means we’re slicing the last 4 digits, which will give us ‘0012’, as we wanted.

Using Array and join

We can also use the Array methods to go about this in a roundabout way.

Why don’t we use the Array() method to create an array of ‘padNum + 1’ elements. This will create an array of length ‘padNum + 1’, while leaving the slots empty.

Then, we can use the ‘join’ method on this array and provide the join condition as ‘0’. This will effectively join an empty array with 0s and create a string of length ‘padNum’.

For example, if we want 2 padded 0’s, use Array(3), which will create the following array: [ , , ]. Now, join that with ‘0’ so the ‘0’ replaces the 2 commas, and you have ‘00’, which can be concatenated with ‘num’., as shown below:

function leadingZeroes(num, padNum) {
  return Array(padNum + 1).join('0') + num;
} 

Adding leading zeros to a negative number in JavaScript

Sometimes, you might be sent negative numbers, and if you convert this number to a string and pad it, you’ll end up with something like this: 00-123. That’s not correct.

So, your program should also check for negative values, and be equipped to handle the same.

Look at the code block below:

1. We’ve created a variable ‘neg’ and assigned it a default value of ‘false’. This value will change to ‘true’ if the number is below 0 (negative number).
2. Then, we’re checking if the number is below 0.
3. If it is, we’re converting the number to a string, and slicing from 1 till the rest of the string (effectively removing the ‘-‘ symbol from the number). Then we’re making ‘neg’ true to indicate that it’s a negative number (so we can add back the ‘-‘ symbol once the padding is done).
4. Then, we can proceed as usual. Pad the string with 0s using the ‘padStart’ method.
5. Finally, while returning the string, let’s use a ‘ternary’ operator to check if ‘neg’ is true. If it is, concatenate the string (padded number) with ‘-‘, otherwise, return it as it is.

function leadingZeroes(num, length) {
  let neg = false;
  if(num < 0) {
      num = num.toString().slice(1);
      neg = true;
  }
  num = num.toString();
  num = num.padStart(length, '0'); 
  return neg ? '-' + num : num;
}

console.log(leadingZeroes(12,4)); //0012
console.log(leadingZeroes(-12,4)); //0012 

That’s it! We’ve looked at several ways of padding a number with 0s in this tutorial.

Leave a Comment