0

I am having a hard time with this code. I keep getting a rounding error when I enter 95.95 as the purchase price and 100 as the price paid, for example it returns 4 dollars, 4 pennies and not 4 dollars and 5 pennies. All other values work fine but for some reason it is having a hard time returning the correct pennies when the decimal place is .95 or .05...

public static void main(String[] args){

        //Read price per pack
        Scanner in = new Scanner(System.in);

        System.out.println("Enter purchase price: ");
        double purchasePrice = in.nextDouble();
        System.out.println("Enter amount paid: ");
        double amountPaid = in.nextDouble();

        //Compute change due

        if (amountPaid < purchasePrice)
        {System.out.printf("Error, you need more money!");
        }

        else {
        int diff = (int)(( amountPaid - purchasePrice)*100);


        int dollars = diff/100;
            diff = diff%100;

        int quarters = diff/25;
            diff = diff%25;

        int dimes = diff/10;
            diff = diff%10;

        int nickels = diff/5;
            diff = diff%5;

        int pennies = diff/1;
            diff = diff%1;

        System.out.println("--------------------");    
        System.out.println("Total Change due: " + (amountPaid - purchasePrice));
        System.out.println("--------------------");
        System.out.println("Dollars: " + dollars);
        System.out.println("Quarters: " + quarters);
        System.out.println("Dimes: " + dimes);
        System.out.println("Nickels: " + nickels);
        System.out.println("Pennies: " + pennies);

        }
    }
}
Nithin
  • 748
  • 1
  • 10
  • 27

1 Answers1

1

Your problem is the line

int diff = (int)(( amountPaid - purchasePrice)*100);

where you round the number of cents downwards to the next int below 100x the price. Since a double doesn't necessarily represent a decimal number exactly, there can be a floating point error which gets magnified 100x when you do the multiplication. The product can be slightly above or below the integer number of cents, so your rounding can cause the amount to be rounded down, almost a whole cent.

What you actually want to do is round the double value of the number of cents to the closest int, not the next int below. You can do that by adding 0.5 before you round.

int diff = (int)(( amountPaid - purchasePrice)*100 + 0.5);

In general though, you should never use double to store an amount of money, if you want to do exactly calculations with it. I recommend learning to use the BigDecimal class, in which problems like this one just disappear.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110