Change Return

Description: Returns the number of dollars, quarters, dimes, nickles and pennies in change based on the price and the amount tendered.
Tested Platform: .NET 4.6, Visual Studio 2015, Windows 7/10
Language: C#
// Return a string describing how much change is to be issued to the customer.
// Gives the number of dollars, quarters, dimes, nickles and pennies to change.

private String returnChange(decimal price, decimal tender)  {
    if (tender == price) { return "There is no change."; }
    else if (tender >= price) {
        decimal difference = tender - price;

        int dollars = (int)(difference / 1m);
        decimal remainder = difference % 1m;

        int quarters = (int)(remainder / .25m);
        remainder %= .25m;

        int dimes = (int)(remainder / .10m);
        remainder %= .10m;

        int nickles = (int)(remainder / .05m);
        remainder %= .05m;

        int pennies = (int)(remainder / .01m);
        remainder %= .01m;

        return "Dollars: " + dollars + " Quarters: " + quarters + " Dimes: " + dimes + " Nickles: " + nickles + " Pennies: " + pennies;
    }
    else {
        return "Sorry, but the amount tender does not cover the price. Please give more money.";
    }
}

Submitted: April 25, 2013

Return to the snippets listing