In JavaScript, we can convert an integer to a string and add leading zeros to it by making use of the addition operator (+). Let’s say we have the integer 456 and we want to add 3 zeros to the front of it. Here is the code to do this:
var num = 456;
var convertedNumber = "000" + num;
console.log(convertedNumber);
#Output:
000456
By using the addition operator + between a string and a number like we did above, we will concatenate the number to a string. So we do not need to convert the integer to a string using something like the toString() method. We just need the addition operator + and that’s it.
Let’s put our code in a function so we can add as many leading zeros as we want to any number. To make it so we add as many zeros as the user tells us, we need to make use of the repeat() method.
function addLeadingZeros(number,numZeros){
var numberOfZeros = "0".repeat(numZeros);
return (numberOfZeros + number);
};
And now lets see our function in action with an example:
function addLeadingZeros(number,numZeros){
var numberOfZeros = "0".repeat(numZeros);
return (numberOfZeros + number);
};
console.log(addLeadingZeros(456,3));
#Output:
000456
When working with integers, the ability to modify the values of the variables easily is valuable.
One such situation is when you have an integer and want to convert it to a string and add leading zeros to the string.
Many times, when you are working with data that has an ID or a record number, that is represented by a number, you need to add leading zeros to maintain data integrity.
To add leading zeros to a string in JavaScript, the easiest way is with the addition operator +.
Let’s show our function one more time and add some more examples to see it in action.
function addLeadingZeros(number,numZeros){
var numberOfZeros = "0".repeat(numZeros);
return (numberOfZeros + number);
};
console.log(addLeadingZeros(123,3));
console.log(addLeadingZeros(987650987,6));
console.log(addLeadingZeros(123,0));
console.log(addLeadingZeros("00111",2));
console.log(addLeadingZeros(90809281,10));
#Output:
000123
000000987650987
123
0000111
000000000090809281
Hopefully this article has been useful for you to learn how to use JavaScript to add leading zeros.