Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove thousand separators from string amount using a regex

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.

Examples:

  • 1,234,567.00 needs to become 1234567.00
  • 1,234.00 needs to become 1234.00
    but
  • 1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
  • 1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)

I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:

myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");

What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.

like image 496
user2571510 Avatar asked Nov 24 '14 13:11

user2571510


People also ask

How do you remove commas in regex?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

What is the thousand separator format?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.


1 Answers

This one may suit your needs:

,(?=[\d,]*\.\d{2}\b)

Regular expression visualization

Debuggex Demo

like image 102
sp00m Avatar answered Sep 23 '22 22:09

sp00m