Parse a String with Commas to a Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 22, 2021

banner

Check out my new book

Parse a String with Commas to a Number #

To parse a string with commas to a number:

  1. Use the replace() method to remove all the commas from the string.
  2. The replace method will return a new string containing no commas.
  3. Convert the string to a number.
index.js
const str = '12,000,000.50'; const num = parseFloat(str.replace(/,/g, '')); console.log(num); // 👉️ 123000000.5

In the code snippet we used the String.replace method to remove all the commas from the string.

The first parameter we passed to the method is a regular expression and the second a replacement for each match of the regular expression.

The forward slashes / / mark the start and end of the regular expression.

In our regex, we only match a comma. Notice that we use the g (global) flag, because we want to match all occurrences of a comma in the string and not just the first one.

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

Because we want to remove all commas, we replace each comma with an empty string.

The last step is to call the parseFloat function on the result.

The parseFloat function takes a string as a parameter and returns a floating point number.

If the parseFloat function cannot convert the string to a number (the string contains non-numeric characters), it returns NaN (not a number).

Here are some examples of using the parseFloat function.

index.js
console.log(parseFloat('100')); // 👉️ 100 console.log(parseFloat('100.5')); // 👉️ 100.5 console.log(parseFloat(10.5)); // 👉️ 10.5 console.log(parseFloat('a123')); //👉️ NaN

If you are looking to avoid using regular expressions, you can use the String.replaceAll method instead of replace.

index.js
const str = '12,000,000.50'; const num = parseFloat(str.replaceAll(',', '')); console.log(num); // 👉️ 123000000.5

This code snippet achieves the same result, however instead of passing a regex as the first parameter, we pass a string containing a comma.

The second parameter is the replacement for each match, just like with the replace method.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.