Add trailing Zeros to a Number in JavaScript


Borislav Hadzhiev

Last updated: Oct 26, 2021


Photo from Unsplash

Add trailing Zeros to a Number in JavaScript #

To add trailing zeros to a number:

  1. Convert the number to a string.
  2. Use the padEnd() method to add trailing zeros.
  3. The padEnd method returns a string of a specified target length, padded with the supplied character at the end.
function addTrailingZeros(num, totalLength) { return String(num).padEnd(totalLength, '0'); } console.log(addTrailingZeros(1.1, 5)); // 👉️ "1.100" console.log(addTrailingZeros(-1.5, 5)); // 👉️ "-1.50" console.log(addTrailingZeros(1, 2)); // 👉️ "10" // 👇️ Alternatively, just use the addition (+) operator const num = 5.3 + '00'; // 👉️ "5.300" console.log(num);

We passed the following parameters to the padEnd method:

  1. the target length for the string
  2. the pad string

The padEnd method returns a string of the specified target length that is padded with the provided pad string.

If you were to convert the string back to a number, the trailing zeros from decimal numbers would get automatically dropped. This is because the number 5.00 is the same as 5 and JavaScript doesn't keep insignificant trailing zeros around.
console.log(5.00 === 5); // 👉️ true

When using the padEnd method you have to take into consideration that even the minus - sign or the dot . are counted in the target length.

This can be confusing in some scenarios. Sometimes it's better to just use the addition (+) operator instead.

console.log(5.5 + '00'); // 👉️ 5.500 console.log(-5.5 + '00'); // 👉️ -5.500

When using the addition operator with a number and a string, the number gets converted to a string and the two strings get concatenated.

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.