How to Parse String with Commas to Number in JavaScript
Table of Contents
When you're working with external data or APIs, sometimes you will get back numbers in the form of strings.
The problem with this is that sometimes, these numbers will include commas, which will make it harder to parse.
There are several ways to address this issue. In this post, we'll look at the best solution for parsing a string with commas into a number.
Removing the commas
The most straightforward way to convert a string with commas into a number is to simply remove the commas in the string first.
Let's start with our example string:
JAVASCRIPTconst string = "1,000,000";
Now we'll use the replace
method to globally replace all commas with an empty string, essentially removing the commas:
JAVASCRIPTconst string = "1,000,000";
const stripped = string.replace(/,/g, "");
Alternatively, we can use the replaceAll
method to replace all commas with an empty string:
JAVASCRIPTconst string = "1,000,000";
const stripped = string.replaceAll(",", "");
Either way, from here we can just use the parseFloat
method to convert the string into a number:
JAVASCRIPTconst string = "1,000,000";
const stripped = string.replace(/,/g, "");
const number = parseFloat(stripped);
console.log(number);
BASH1000000
Alternatively, if you want an integer, you can use the parseInt
method:
JAVASCRIPTconst string = "1,000,000";
const stripped = string.replace(/,/g, "");
const number = parseInt(stripped);
console.log(number);
BASH1000000
As long as the string does not contain any non-numeric characters, it will successfully parse into a number that you can use.
Conclusion
In this post, we learned how to remove commas from a string and then parse it into a number.
You can use either the replace
or replaceAll
methods to remove commas from a string, then use parseFloat
or parseInt
to convert the string into a number.
Thanks for reading and happy coding!
- Getting Started with Solid
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Getting Started with Moon.js