Java method working with an int but not a double

Advertisements

When I call the method with 142.14, I don’t get any errors, but nothing prints to the console at all. When I send 142, it works as intended. Why is this?
This code is in Java and I need to add more details to ask this question so here I am adding more details.

public class Testing {
    static int twentyCount = 0;
    static int tenCount = 0;
    static int fiveCount = 0;
    static int dollarCount = 0;
    static int quarterCount = 0;
    static int dimeCount = 0;
    static int nickelCount = 0;
    static int pennyCount = 0;
    
    public static void main(String[] args) {
        
        returnChange(142.14);
    }
    
public static void returnChange(double change) {
        
    
        while (change >= 1.0) {
            if(change >= 20.0) {
                change = change - 20.0;
                twentyCount++;
                continue;
            } if(change >= 10.0) {
                change = change - 10.0;
                tenCount++;
                continue;
            } if(change >= 5.0) {
                change = change - 5.0;
                fiveCount++;
                continue;
            } if(change >= 1.0) {
                change = change - 1.0;
                dollarCount++;
                continue;
            }
        }
        while (change != 0.0) {
            if(change >= .25) {
                change = change - .25;
                quarterCount++;
                continue;
            } if(change >= .1) {
                change = change - .1;
                dimeCount++;
                continue;
            } if(change >= .05) {
                change = change - .05;
                nickelCount++;
                continue;
            } if(change >= .01) {
                change = change - .01;
                pennyCount++;
                continue;
            }
        }
    System.out.println("Change dispensed:  " + twentyCount + " 20's, " + tenCount + " 10's, " + fiveCount + " 5's, "
                + dollarCount + " 1's, " + quarterCount + " quarters, " + dimeCount + " dimes, "
                + nickelCount + " nickels, and " + pennyCount + " pennies.");
    }
    

}

>Solution :

Consider this. Change could be .009999 and thus not be updated by any of the conditions. And it would also fail equality to 0.0. So it would run forever. So in this case, do:

while (change >= .01) // the smallest value you care about.
     ...
     ...
     ...
    } if(change >= .01) {
        change = change - .01;
        pennyCount++;
        continue;
    }
}

It will still update the cents and exit properly. In future situations, either express your money in cents (e.g. 143.14 is 14314 cents) or use BigDecimal for calculations. In general, don’t use double values for money.

Leave a ReplyCancel reply