Categories
JavaScript Answers

How to convert string with dot or comma as decimal separator to number in JavaScript?

Spread the love

Sometimes, we want to convert string with dot or comma as decimal separator to number in JavaScript.

In this article, we’ll look at how to convert string with dot or comma as decimal separator to number in JavaScript.

How to convert string with dot or comma as decimal separator to number in JavaScript?

To convert string with dot or comma as decimal separator to number in JavaScript, we use the string replace method.

For instance, we write

const num = parseFloat(str.replace(",", ".").replace(" ", ""));

to call replace to replace commas with periods and spaces with with empty strings.

Then we call parseFloat to convert the string into a decimal number and return it.

Conclusion

To convert string with dot or comma as decimal separator to number in JavaScript, we use the string replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *