Yes remove the commas:
let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);
Answer from Sam on Stack OverflowYes remove the commas:
let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);
Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).
I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299
The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(
The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/
The two best JS options I've come across for this so far:
- https://github.com/google/closure-library/tree/master/closure/goog/i18n
- https://github.com/globalizejs/globalize
Javascript Formatting numbers with commas
In JavaScript / jQuery what is the best way to convert a number with a comma into an integer? - Stack Overflow
How to convert a number with comma as string into float number in Javascript - Stack Overflow
Parsing a number that uses comma as the decimal separator
The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)
One way is to remove all the commas with:
strnum = strnum.replace(/\,/g, '');
and then pass that to parseInt:
var num = parseInt(strnum.replace(/\,/g, ''), 10);
But you need to be careful here. The use of commas as thousands separators is a cultural thing. In some areas, the number 1,234,567.89 would be written 1.234.567,89.
Try:
parseFloat('1,022.55'.replace(/,/g, ''))
Here it is annotated
originalNum = '1,022.55';
cleanNum = originalNum.replace(",", "");
float = parseFloat(cleanNum);
console.log(float);
Alternatively you can just make it a one-liner by using
float = parseFloat('1,022.55'.replace(",", ""));
console.log(float);