0

I'm trying to make a program that takes an input amount and separates them into how many coins it would equal. So far what i wrote gives me the right amount most of the time but sometimes it will be a penny off and i don't know why.

public static void main(String[] args) {
    double amount;
    System.out.println("This program will display the number of "
            + "quarters, dimes, nickels and pennies based on the "
            + "amount you enter below.");
    System.out.println();
    System.out.print("Please enter an amount: ");
    Scanner scan = new Scanner(System.in);
    amount = scan.nextDouble();

    double quarter = amount/0.25;
    amount = amount % 0.25;
    double dime = amount/0.10;
    amount = amount % 0.10;
    double nickel = amount/0.05;
    amount = amount % 0.05;
    double penny = amount/0.01;


    System.out.println("Quarters: " + (int)quarter);
    System.out.println("Dimes " + (int)dime);
    System.out.println("Nickels " + (int)nickel);
    System.out.println("Pennies " + (int)penny);

When i input 2.47, i get:

Please enter an amount: 2.47
Quarters: 9
Dimes: 2
Nickels: 0
Pennies: 2

But when i input 1.47, i get:

Please enter an amount: 1.47

Quarters: 5
Dimes: 2
Nickels: 0
Pennies: 1
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • If you take a look [here](https://ideone.com/OHhyCJ), you'll see it's actually 1.99...62, because of inaccurate floating point arithmetic. When you cast to integer, decimal places are completely truncated. – Andrew Li Oct 08 '16 at 02:50

1 Answers1

0

The most likely reason for your problem is that floating point arithmetic is subject to rounding errors. At a certain point, one of the intermediate floating point results is not completely accurate, and the error is amplified when you use a cast to convert the double to an int.

For a full explanation of why this sort of thing happens, read the answers to Is floating point math broken?

Solution You should recode this using the int (or long) type to represent a whole number of cents.

Start with this:

long amount = (long) (100 * scan.nextDouble());

and then recode the rest of the method accordingly.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216