-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

3
  • Double.parseDouble? Commented Mar 30, 2016 at 13:22
  • @Mena After removing the $ sign. Commented Mar 30, 2016 at 13:22
  • @Hackerdarshi goes without saying. Commented Mar 30, 2016 at 13:25

2 Answers 2

1
public double convertPayment(String inputPayment) {   
    String payment = inputPayment.substring(1);
    double paymentValue = Double.parseDouble(payment);
    return paymentValue;
}
Sign up to request clarification or add additional context in comments.

Comments

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);
      }

2 Comments

the specification says that the input should be with a "$" sign. so 100.00 and 50.00 ... wont be accepted, they should be ($100.00....)
Ok, I edited my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.