Borislav Hadzhiev
Last updated: Oct 22, 2021
Check out my new book
To parse a string with commas to a number:
replace()
method to remove all the commas from the string.replace
method will return a new string containing no commas.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 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.
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.
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
.
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.