Parse a String with Commas to a Number in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

banner

Photo by Fil Mazzarino

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee