Remove Trailing Zeros from a Number in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20211 min read

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.

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

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

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