0

My program is supposed to calculate change:

double purchaseAmount = Double.parseDouble(s1); double amountGiven = Double.parseDouble(s2); double change = purchaseAmount - amountGiven; JOptionPane.showMessageDialog(null, change); String result = "Change consists of:"; 

My change is counted in bills and coins. But once I get to the coins, which are double:

double quarters = 0; if (change >= .25) { quarters = change / .25; change = change - quarters * .25; result = result + quarters + "quarters"; change = change - quarters % .25; } 

The result is giving me a trailing .0 for instance instead of telling me my change is 1 twenty 2 quarters. I get 1 twenty 2.0 quarters. I've tried almost everything, BigDecimal, NumberFormat DecimalFormat(##.###) I already have a String in the program and would not know how to add another.

5
  • You should not try to do exact calculations (which you probably want to do when talking about money) using floating point types. Commented Sep 18, 2014 at 6:23
  • 3
    Given that you can't have a fractional number of quarters, why are you storing that in a double anyway? (Your line of change = change - quarters % .25; looks dubious to me, too...) I would actually suggest that you change the value from dollars to cents to start with, and do everything in integer arithmetic after that. It'll make life much simpler. Commented Sep 18, 2014 at 6:23
  • result + quarters + "quarters" <-- the quarters value should be formatted to a string there according to the desired rules; using an int might be sufficient to "solve" this issue, as such does not contain fractional information to start. Commented Sep 18, 2014 at 6:23
  • @merryprankster: Using floating point probably isn't too bad in itself - it's using binary floating point that causes problems. Using BigDecimal would be okay (if handled carefully in terms of division etc). Commented Sep 18, 2014 at 6:25
  • 1
    Also check out this: Why not use Double or Float to represent currency? Commented Sep 18, 2014 at 6:28

2 Answers 2

0

Try to convert the double value into integer or use integer for your conversions (double will give you floating values)

 result = result + ((int) quarters) + "quarters"; 

or can use Math.round() function to round the values ..

Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't use floats to store monetary values. Use BigDecimal instead.
And then use NumberFormat to format the results for output.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.