-1

I just have a question about adding some currency ($) in JAVA, I used the NumberFormat.getCurrencyInstance(); to get my outputs in "$". My program is to input some money (String format) for example the program only accepts ($100.00, $50.00, $20.00 ... and so on) so I used this code:

String payment = keyboard.next();
while (!(payment.equals("$100.00")) && (!payment.equals("$50.00")) && (!payment.equals("$20.00")) && (!payment.equals("$10.00")) && (!payment.equals("$5.00")) && (!payment.equals("$2.00")) && (!payment.equals("$1.00")) {
System.out.print("Invalid coin or note. Try again. ");
payment = keyboard.next(); }

How can I get the inputs (100.00, 50.00 ... ) as a Double in order to subtract them from the total price.. for example I want (100.00-12.00) (12.00 is the total price)

Any help would be appreciated Thanks

mad_manny
  • 1,081
  • 16
  • 28
A Madridista
  • 73
  • 1
  • 10

2 Answers2

1
public double convertPayment(String inputPayment) {   
    String payment = inputPayment.substring(1);
    double paymentValue = Double.parseDouble(payment);
    return paymentValue;
}
Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
0

If your input is a "$" sign, you can delete the first element of your string and then convert it to a double.

//method to convert String in Double
public Double getDoubleFromString(String payment) 
{
  payment = payment.substring(1);
  double paymentDouble = Double.parseDouble(payment);
  return paymentDouble;
}

String payment = keyboard.next();
double paymentDouble = getDoubleFromString(payment);

while (paymentDouble != 100.00 && paymentDouble != 50.00 && paymentDouble != 20.00 
           && paymentDouble != 10.00 && paymentDouble != 5.00 
           && paymentDouble != 2.00 && paymentDouble != 1.00) 
      {
         System.out.print("Invalid coin or note. Try again.");
         String payment = keyboard.next();
         paymentDouble = getDoubleFromString(payment);
      }
harry-potter
  • 1,981
  • 5
  • 29
  • 55