0

I have some code here that takes a double amount that serves as a dollar amount and outputs the amount of coins it contains. I have been trying to get it to execute "1.69" correctly for a long time, putting in a ridiculous amount of parenthesis to make sure it works; however, the output is never correct. Currently, as it stands below, the output is 6 Quarters, 1 dimes, 1 nickle, and 3 pennies, which is "1.68," and I cannot for the life of me figure out why. Any ideas? Thanks.

ChangeJar2(final double _amount_){

    quarters = (int) (_amount_/.25);// Computes # of quarters
    dimes = (int) ((_amount_-(quarters*(.25)))/.1);// Computes # of dimes
    nickles = (int) ((_amount_-(quarters*(.25))-(dimes*.1))/.05);// Computes # of nickles
    pennies = (int) ((_amount_-(quarters*(.25))-(dimes*(.1))-(nickles*(.05)))/.01);// Computes # of pennies

    System.out.println(quarters + " " + dimes + " " + nickles + " " + pennies);


}// End of ChangeJar(final double _amount_) Constructor
Pig_Mug
  • 167
  • 3
  • 13
  • 1
    We should all not forget the inaccuracy of double. So, OP, you should think about using `BigDecimal` instead. – Tom Jan 19 '15 at 21:59
  • 1
    The duplicate shows you why your program fails. To get correct behavior, use an `int` (just divide by 100 before printing) or `BigDecimal` to represent currency. – Keppil Jan 19 '15 at 21:59
  • 1
    A better way to go about this is to convert to an int that represents the number of cents only once. Take the input such as "1.45" and convert that to 145 first then go from there. That should avoid your problems that stem from the converting from a floating point representation to an int. – shuttle87 Jan 19 '15 at 22:00
  • Thanks shuttle87! I multiplied the amount by 100, and did the division accordingly, it works (: – Pig_Mug Jan 19 '15 at 22:10

0 Answers0