Add trailing Zeros to a Number in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

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.
index.js
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.
index.js
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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee