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

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.