Home  >  Article  >  Web Front-end  >  How to Correctly Parse a String with Comma Thousand Separators in JavaScript?

How to Correctly Parse a String with Comma Thousand Separators in JavaScript?

DDD
DDDOriginal
2024-11-22 12:01:12989browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn