0

I'm attempting to write a method where the input is an amount of money and it returns the minimum amount of pennies needed for that dollar amount (ex. 1.11 would have one penny). My code works for smaller numbers for breaks with bigger numbers.

public static void main (String[] args) {
    int result = (lessPennies(200.0));
    System.out.println(result);
}

public static int lessPennies(double n) {
    double pennies = n % .05;

    pennies = (pennies * 100);
    pennies = Math.round(pennies);
    
    int penniesReturn = (int) pennies;
    return penniesReturn;
}

I'm expecting the output here for pennies to be zero, given that 200 / .05 is 4000 and should not have anything left over, yet I get 5 as an answer. I understand why this happens but I'm not sure how to fix it and not break the code for smaller inputs.

  • 3
    You're about to be swamped by recommendations to not use doubles, or floats, to represent amounts of money ... let me join the chorus - represent your amounts as integers (so a dollar would have 100 pennies, etc) and you have sufficient control over the arithmetic to do as you wish. Many, many, many other Qs and As on this site to give your same advice, sometimes with different solutions. – High Performance Mark Oct 31 '22 at 14:37
  • Long past time for a Money class to encapsulate all this. https://www.baeldung.com/java-money-and-currency – duffymo Oct 31 '22 at 14:38
  • @HighPerformanceMark What if you are forced to use a double as the parameter type by an instructor? If I multiply the double by 100 and cast it as an integer will I have the same issue? – user20380103 Oct 31 '22 at 14:57
  • Is the instructor armed? If so follow the instructions. As to the question you ask in the comment (tut tut), yes, you can't avoid the difficulties attached to representing monetary amounts in floating-point numbers by, well, by using floating-point numbers multiplied by 100. – High Performance Mark Oct 31 '22 at 14:59
  • An instructor could use this as an important teaching moment to instruct on floating point numbers and precision. Sounds like they'll miss the chance. – duffymo Oct 31 '22 at 15:01

0 Answers0