Home > Article > Web Front-end > How to Correctly Parse a String with Comma Thousand Separators in JavaScript?
Parsing String with a Comma Thousand Separator to a Number
When attempting to parse a string containing a comma as a thousand separator, using parseFloat can result in incorrect conversion. This is because the comma is interpreted as a decimal separator.
To resolve this issue, you can remove the commas before parsing the string as a number.
const stringWithComma = "2,299.00"; const output = parseFloat(stringWithComma.replace(/,/g, '')); console.log(output); // 2299
In this example, the replace method is used to replace all occurrences of the comma with an empty string. This effectively removes the commas from the string, allowing parseFloat to correctly parse it as a number.
The above is the detailed content of How to Correctly Parse a String with Comma Thousand Separators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!