Parse a String with Commas to a Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 14, 2022

banner

Photo from Unsplash

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

We used the String.replace method to remove all of the commas from the string.

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

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

We only match a comma in the regular expression.

index.js
const str = '12,000,000.50'; const num = parseFloat(str.replace(/,/g, '')); console.log(num); // 👉️ 123000000.5
We used the g (global) flag because we want to match all occurrences of a comma in the string and not just the first occurrence.

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

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

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

The parseFloat function parses the provided string and returns a floating point number.

If the parseFloat function cannot convert the string to a number, because the string contains non-numeric characters, the method 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're looking to avoid using a regular expression, use the String.replaceAll method.

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, we passed a string instead of a regular expression to the replaceAll() method.

The second parameter is the replacement for each match.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.