8

Suppose I'm supplied with a String which is like "$123,456,56.25" or "123'456.67" or something similar to this (with digits and a decimal point and some seperator like , or ' or something else which is not predictable). I need to write a method which takes an argument like the one above and returns a String like "12345656.25" or "123456.67" respectively.

Could you please suggest the most efficient and readable code to achieve this?

Note: I'm aware of going through each indexes and checking for whether its retunrs true for Character.isDigit(charAtInedx) or if(charAtInedx == '.') I'm looking for a more optimized solution both in terms of efficiency and readability

Thanks.

Mat
  • 202,337
  • 40
  • 393
  • 406
nobody
  • 1,909
  • 5
  • 31
  • 45

2 Answers2

18
String newStr = oldStr.replaceAll("[^\\d.]+", "")

This will drop any character that is not either a digit or a period

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 2
    @jarnbjo Please re-read the question: with digits and **a decimal point** and some seperator – Sean Patrick Floyd May 16 '11 at 11:21
  • Even I'm not sure about the variety of inputs this method may receive. But looking at the current code I'm sure the regular expression you suggested would suffice. Thanks. – nobody May 16 '11 at 11:37
  • `00000000042.` will pass that RegEx and that doesn't look like a valid currency value to me. – Madbreaks Feb 12 '18 at 23:07
  • @Madbreaks you're absolutely right. This is not a universal currency fixer, but a regex for the specific situation the OP mentioned. – Sean Patrick Floyd Feb 13 '18 at 01:07
  • Sure. But reading op's title it's clear what the intent here is, and I don't think allowing a string of fifty decimal points is _helpful_. It may technically satisfy what op said but a better answer would have provided some/additional guidance IMO. – Madbreaks Feb 13 '18 at 17:50
  • @Madbreaks feel free to provide that answer – Sean Patrick Floyd Feb 13 '18 at 19:56
7

If you want to handle monetary values correctly, you will want to have a look at the NumberFormat class, specifically for your case NumberFormat.parse(String). The following article also discusses the problems (and solutions) to handling money in Java:

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

Other related classes include: Currency and of course BigDecimal.

Alan Escreet
  • 3,499
  • 2
  • 22
  • 19