In JavaScript, we can convert an integer to a string and add trailing 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 end of it. Here is the code to do this:

var num = 456;
var convertedNumber = num + "000";

console.log(convertedNumber);

#Output:
456000

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 trailing 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 addTrailingZeros(number,numZeros){
  var numberOfZeros = "0".repeat(numZeros);
  return (number + numberOfZeros);
};

And now lets see our function in action with an example:

function addTrailingZeros(number,numZeros){
  var numberOfZeros = "0".repeat(numZeros);
  return (number + numberOfZeros);
};

console.log(addTrailingZeros(456,3));

#Output:
456000

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 trailing 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 trailing zeros to maintain data integrity.

To add trailing 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 addTrailingZeros(number,numZeros){
  var numberOfZeros = "0".repeat(numZeros);
  return (number + numberOfZeros);
};

console.log(addTrailingZeros(123,3));
console.log(addTrailingZeros(987650987,6));
console.log(addTrailingZeros(123,0));
console.log(addTrailingZeros("00111",2));
console.log(addTrailingZeros(90809281,10));

#Output:
123000
987650987000000
123
0011100
908092810000000000

Hopefully this article has been useful for you to learn how to use JavaScript to add trailing zeros.

Categorized in:

JavaScript,

Last Update: February 26, 2024