Search code examples
javaroundingcoin-change

Rounding Error?


Hi I'm having an issue while creating a change calculator for a school assignment. It essentially is to calculate the lowest amount of change needed for a certain amount of money.

  • Ex. $5.36:
  • 2 toonies (2$)
  • 1 loonie (1$)
  • 1 quarter
  • 1 dime
  • 0 nickels
  • 1 penny

I've stated all of my variable to be doubles so I can calculate the values and the totals together. It seems to work fine on whole numbers (5.00, 6.00, 7.00) but messes up whenever I add a decimal place. Like when I say $5.25 it should say 2 toonies 1 loonie and 1 quarter. I think it could be an error in rounding or something wrong with my calculations. Any Help is appreciated. Here is the calculations of the code:

//Rounding to one number           
DecimalFormat oneDigit = new DecimalFormat ("#,0");

//Ask user for input
String moneyinput = JOptionPane.showInputDialog ("Welcome to the Change Caluculator. "
                + "Please Enter your amount of money in Dollars ($): ");

//Take user input and create into string.
totmoney = Double.parseDouble (moneyinput);

//Calculate number of toonies
numtoonies =  (totmoney/toonieval);

System.out.println ("There is a total of " + oneDigit.format (numtoonies) + " toonies.");

//Find new amount
totmoney = (totmoney%toonieval);

//Calculate the number of loonies
numloonies = (totmoney/loonieval);

//Find new amount
totmoney = (totmoney-numloonies);

System.out.println ("There is a total of " + oneDigit.format (numloonies) + " loonies.");

//Calculate number of quarters
numquarters = (totmoney/quarterval);

//State the about of Coins
System.out.println ("There is a total of " + oneDigit.format (numquarters) + " quarters.");
}

Solution

  • I don't quite understand why you are using the DecimalFormat at all. You should be able to do solve this with only mod % and division /.

    This is how I would approach this problem:

    1. Take the input from the user (as a double in the format 5.33)
    2. Save that as int by moving the decimal place (int value = cost * 100)
    3. Find the number of toonies by using division (numToonies = value / toonieval)
    4. Find the remaining amount of money by (value = value % toonieval)
    5. Repeat steps 3 and 4 for the other denominations

    Note: you will have to modify the values of the toonies to reflect the fact that the price you used was multiplied by 100.