0

I am working on a program in which you enter the amount and it breaks it up into change. However, I am currently struggling because it does not work for some test cases such as "2.03". I tried finding where the problem was and for some reason after I find the amount of quarters and subtract it from the amount, it does not subtract properly. I would really appreciate it if someone could help me out.

import java.util.Scanner;

public class Exercise9 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Amount : ");
    double amount = input.nextDouble();

    double quarters = amount / 0.25;
    quarters = quarters - (quarters % 1);
    amount = amount - (quarters * 0.25);
    System.out.print("\n" + amount);
    double dimes = amount / 0.10;
    dimes = dimes - (dimes % 1);
    amount = amount - (dimes * 0.10);
    double nickels = amount / 0.05;
    nickels = nickels - (nickels % 1);
    amount = amount - (nickels * 0.05);
    double pennies = amount / 0.01;
    pennies = pennies - (pennies % 1);


    System.out.print("\nQuarters : ");
    System.out.printf("%.2f", quarters);
    System.out.print("\nDimes    : ");
    System.out.printf("%.2f", dimes);
    System.out.print("\nNickels  : ");
    System.out.printf("%.2f", nickels);
    System.out.print("\nPennies  : ");
    System.out.printf("%.2f", pennies);
    System.out.print("\n" + amount);
}
 }
John
  • 1
  • Welcome to SO! Don't forget to check the guidelines. – Spectric Sep 18 '20 at 22:46
  • @IronMan one of the test cases that fails is 2.03. The operation that gives me an unexpected result is line 12 "amount = amount - (quarters * 0.25);" I expect to get 0.03 but instead I get 0.029999999999999805 – John Sep 18 '20 at 22:50
  • Are you allowed to convert the input number into cents and do all your computations with ints or longs instead of doubles? – Mark Plotnick Sep 18 '20 at 22:58
  • @john https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Federico klez Culloca Sep 18 '20 at 23:00
  • @MarkPlotnick yes i guess i could but do you happen to know why I am getting this problem where the subtraction gets messed up – John Sep 18 '20 at 23:01

0 Answers0