0

Working on a simple java program that should only accept an input that is in .05 cent increments. When attempting to use the mod operator for data validation, I am getting some weird, unexpected results:

        public static void takePayment(double itemCost){
    DecimalFormat df = new DecimalFormat("#.00");
    System.out.println(itemCost);
    Scanner input = new Scanner(System.in);
    System.out.println("Please insert $" + df.format(itemCost) + " into the machine");
    System.out.println("Type the amount you are inserting into the machine.");
    System.out.print("$");

    if (!input.hasNextDouble()){
        System.out.println("Please enter the amount inserted in X.XX format");
        takePayment(itemCost);
    }
    double amtInsert = 0;
    amtInsert = input.nextDouble(); 
    double remainder = 0;

    remainder = amtInsert %(0.05);
    System.out.println(remainder);

    if (remainder == 0)
    {
        System.out.println("works");
    }else{
        System.out.println("Invalid amount inserted, this machine only accepts Nickels, Dimes, Quarters, "
                + "1 dollar bills, and 5 dollar bills ");
        takePayment(itemCost);
    }


}

If a dollar amount such as 1.25 is entered into the function, it returns:

Please insert $1.25 into the machine
Type the amount you are inserting into the machine.
$1.25
0.04999999999999993
Invalid amount inserted, this machine only accepts  Nickels, Dimes, Quarters, 1 dollar bills, and 5 dollar bills.

Can someone explain why (1.25 % .05) = 0.04999999999999993

Keep in mind while reading my code that I haven't written the rest of the validation, I am only concerned with the modulus at the moment

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • https://stackoverflow.com/questions/4937402/moving-decimal-places-over-in-a-double – assylias Oct 23 '17 at 13:21
  • 1
    Round the value to two decimal places if you need precise values – OneCricketeer Oct 23 '17 at 13:22
  • You can solve this by counting cents instead of dollars - you can then store them in an `int` or `long` which will give exact results. – assylias Oct 23 '17 at 13:22
  • If you'd like to rephrase your question to ask why that doesn't evaluate to 0, then I'll reopen it. However, other modulo calculations online return `0.05`, so you may want to look up the calculation that's really being done – OneCricketeer Oct 23 '17 at 13:32
  • I got it figured out. Thanks for pointing me to the other thread, it helped me solve it! – Jacob Zayak Oct 23 '17 at 14:18

0 Answers0