Remove Trailing Zeros from a Number in JavaScript


Borislav Hadzhiev

Last updated: Oct 23, 2021


Photo from Unsplash

Remove Trailing Zeros from a Number #

To remove the trailing zeros from a number, pass the number to the parseFloat() function. The parseFloat function parses the provided value, returning a floating point number, which automatically removes any trailing zeros.

const num1 = 13.453000; const r1 = parseFloat(num1); console.log(r1); // 👉️ 13.45 // 👇️ if you need to set specific # of decimals // use the toFixed method const num2 = 13.453000; const r2 = parseFloat(num2.toFixed(3)); console.log(r2); // 👉️ 13.453 // 👇️ if the value is a string const str = '13.453000'; const r3 = parseFloat(str); console.log(r3); // 👉️ 13.453

In our first example, we called the parseFloat function to strip all unnecessary trailing zeros from a number.

The only parameter the function takes is a value that it parses to a floating point number.

In the second example, we used the toFixed method on the number to explicitly set the number to 3 decimal places.

The toFixed method returns a string representation of the number with the specified number of decimals.

The toFixed method also rounds the number if necessary and pads the fractional part with zeros if you've specified more decimal places than the number has.

console.log((5).toFixed(2)); // 👉️ '5.00' console.log((5.346).toFixed(2)); // 👉️ '5.35'

In our third example, we have a string, from which we want to remove the trailing zeros. Again, we used the parseFloat function to convert the string to a number.

Numbers in JavaScript automatically drop any unnecessary trailing zeros because 3.00 is equal to 3.

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.