To add leading zeros to a number in Javascript, you can use the padStart() method. Follow this tutorial to understand it.

### Step 1: Convert from Number to String

There are many ways to add Leading Zeros to a Number in JavaScript, but in this article, I use the toString() method. With this method, you can pass in the parameter, but it must be an integer from 2 to 36. Its effect is to output the string with the radix that the parameter has passed (Ex: 2 is binary, 16 is hexadecimal).

We have the number 8 to cast toString(). I would do the following:

var myNum = 8;
console.log(++myNum);
console.log(myNum.toString() + 7);

Output:

9
97

The first console.log() statement, we see it as a normal numeric addition (8 + 1 = 9), but in the second console.log() we see this as a string addition (‘9’ + ‘7’ ==> ’97’) infer now I have converted the variable myNum from number to string. I’m doing this because the padStart() method is only for strings.

Syntax:

padStart(totalLength, padString)

Parameters:

• totalLength: is the total number of characters of the string you want to change, including the initial number, the extra character here is leading zeros and the sign (-) if the given number is negative.
• padString: is a string that will usually be a character you want to add to the beginning when the number of characters in the string is not equal to totalLength.

Example:

var myNum = 8;
var myNum2 = -1;

console.log(myNum2.toString().padStart(5, "0"));

Output:

00008
000-1

As you can see, if the case is positive, the program outputs typically, but in the case of negative numbers, the output is not correct, so I give you the following solution:

var myNum = 8;
var myNum2 = -1;

if (numb < 0) {
const ABS = String(numb).slice(1); // ABS: Absolute value
}

}

console.log(addLeadingZeros(myNum2, 5))

Output:

00008
-00001

With the above method, the string output to the screen is still correct, even if you pass a negative or positive number. You see, I used string.slice() to separate the negative sign from the given number, then the given number returns to a positive number, so we handle it, as usual, just adding a sign (-) in front of the previous string.

## Summary

You can also add Leading Zeros by using the (+) operator to add the number, but this will not work well when the number of Leading Zeros is large, so I still recommend you to use string.padStart() to understand how to add leading zeros to a number in JavaScript.

Maybe you are interested: