You can use the parseFloat() method to remove trailing zeros from a number in JavaScript. The parseFloat() method parses a string into a floating point number while removing all the trailing zeros.

const num = 3.50000
const res1 = parseFloat(num)
console.log(res1) // 3.5

// parse the string back to a number
const str = '6.870000'
const res2 = parseFloat(str)
console.log(res2) // 6.87

The parseFloat() method parses the given string and returns a floating point number without trailing zeros.

If you need to set a specific number of decimal places, use the toFixed() method. The toFixed() method returns a string representation of the number with the specified decimals.

const num = 2.347000
const res = parseFloat(num.toFixed(2))
console.log(res) // 2.35

As you can see above, the toFixed() method rounds the number if required and pads the fractional part with zeros if the specified decimal places are more than the number has.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.