0

Note: Java

I have a String[] called moneyEntered.

moneyEntered[0] has the value "$5.00"

I wish to create a new double (called amountPendingDeduction) which extracts the value "5.00" from moneyEntered[0] (i.e. removing the dollar sign and making the rest a double).

How do I do this?

  • 3
    remove the `$` sign and use `Double.parseDouble(String)`. Note, doubles or floating point primitives arent the best option if you want to represent currencies. – SomeJavaGuy Apr 04 '16 at 09:30
  • @kevinEsche Is there a way to do it without removing the dollar sign? The string moneyEntered itself is inputted by the user, and they will input "$5.00". Also, what is the best to use for currency? BigDecimal? –  Apr 04 '16 at 09:32
  • Check out this answer http://stackoverflow.com/questions/5769669/convert-string-to-double-in-java – Nelson Almendra Apr 04 '16 at 09:34
  • @dearv i think there´s no way around it. Yes `BigDecimal` is a better option. You wont have to deal with precision loss here. – SomeJavaGuy Apr 04 '16 at 09:36
  • Check this link http://stackoverflow.com/questions/23990805/converting-different-countrys-currency-to-double-using-java – Jeet Apr 04 '16 at 09:40

2 Answers2

1

If you are working with currency, double is just fine:

String money = moneyEntered[0].substring(1);
double moneyValue = Double.parseDouble(money);
Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
0

Try:

Double amountPendingDeduction = Double.parseDouble(moneyEntered[0].replace("\\$", ""));

Since String is immutable, nothing will happen with the dollar sign in the moneyEntered[0] string.

Gregory Prescott
  • 574
  • 3
  • 10