Borislav Hadzhiev
Tue Oct 26 2021·2 min read
Photo by Jonathan J. Castellon
To add trailing zeros to a number:
padEnd()
method to add trailing zeros.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:
The padEnd
method returns a string of the specified target length that is
padded with the provided pad string.
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.