Parsing Currency String in java

Suppose I am provided with a string that looks like "$123,456,56.25" or "123'456.67" or something similar to this (with numbers and decimal point, as well as with some type delimiter , or ' ) or something else that are not predictable). I need to write a method that takes an argument like the one above and returns a string like "12345656.25" or "123456.67" respectively.

Could you suggest the most efficient and readable code for this?

Note. I know that I look at each index and check if its retunrs are true for Character.isDigit(charAtInedx) or if(charAtInedx == '.') I am looking for a more optimized solution both in terms of efficiency and readability.

Thanks.

+6
source share
2 answers
 String newStr = oldStr.replaceAll("[^\\d.]+", "") 

This will result in the loss of any character that is neither a digit nor a period.

+11
source

If you want to handle monetary values ​​correctly, you need to take a look at the NumberFormat class, especially for your case NumberFormat.parse (String) . The following article also discusses the problems (and solutions) of money processing in Java:

http://www.javapractices.com/topic/TopicAction.do?Id=13

Other related classes include: Currency and, of course, BigDecimal .

+6
source

Source: https://habr.com/ru/post/888206/


All Articles