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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Nikron69
  • 5
  • 3
  • You should not try to do exact calculations (which you probably want to do when talking about money) using floating point types. – merryprankster Sep 18 '14 at 06: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. – Jon Skeet Sep 18 '14 at 06: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. – user2864740 Sep 18 '14 at 06: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). – Jon Skeet Sep 18 '14 at 06:25
  • 1
    Also check out this: [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) – icza Sep 18 '14 at 06:28

2 Answers2

0

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

jwenting
  • 5,505
  • 2
  • 25
  • 30
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 ..

Sampath Kumar
  • 4,433
  • 2
  • 27
  • 42