Categories
JavaScript Answers

How to parse numbers with comma decimal separators in JavaScript?

Spread the love

Sometimes, we want to parse numbers with comma decimal separators in JavaScript.

In this article, we’ll look at how to parse numbers with comma decimal separators in JavaScript.

How to parse numbers with comma decimal separators in JavaScript?

To parse numbers with comma decimal separators in JavaScript, we can remove all the comma separators with the JavaScript string’s replace method.

Then we can use Number to parse the number.

For instance, we write:

const n = '123,456.789'
const num = n.replace(/,/g, '');
const parsed = Number(num)
console.log(parsed)

to call n.replace to replace all the commas with empty strings.

Then we call Number with num to convert num to a number.

As a result, parsed is 123456.789.

Conclusion

To parse numbers with comma decimal separators in JavaScript, we can remove all the comma separators with the JavaScript string’s replace method.

Then we can use Number to parse the number.

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 *