Remove trailing zeros from a number in JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.