0

I have a String that represents a dollar amount and am trying to use .replaceAll("$", "") on it to prepare it for use with parseDouble(). However, when I run my app I'm still getting a java.lang.NumberFormatException: Invalid double: "$100.00" so it seems that for whatever reason, replaceAll() isn't working. Can anyone suggest why?

Here's the block of code affected:

public String subtractCurrenciesToString(String value1, String value2){
    String stringValue1 = value1.replaceAll("$", "");
    String stringValue2 = value2.replaceAll("$", "");

    Double currency1 = Double.parseDouble(stringValue1);
    Double currency2 = Double.parseDouble(stringValue2);

    return MoneyFormat.format(currency1 - currency2);
}

NOTE: MoneyFormat is a NumberFormat object initialized with getCurrencyInstance().

Argus9
  • 1,863
  • 4
  • 26
  • 40
  • For what it's worth if you are doing any calculations with your money values you really should not be using Double to store it. See Here for a great explanation why: http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – FoamyGuy May 18 '13 at 02:36
  • Interesting read Foamy, thanks. Still, as long as I'm rounding before storing the data, it avoids the dangers of wildly divergent number errors. – Argus9 May 18 '13 at 04:33

1 Answers1

6

replaceAll accepts a regex. In regex, $ is an end-of-string anchor, so you have to escape it in order to use it literally as a dollar sign:

.replaceAll("\\$", "");
Blender
  • 289,723
  • 53
  • 439
  • 496
  • That makes sense, but I tried the correction you mentioned and I'm still getting the $ in my String when I parseDouble(). – Argus9 May 18 '13 at 05:14