Make Change

Description: Prints how many dollars, quarters, dimes, nickels and pennies are in a given currency value.
Tested Platform: Java SE 7, Windows 7
Language: Java
public void makeChange(double currency) {
		double currencyValue = (currency * 100.0);
		long dollars = 0L;
		long quarters = 0L;
		long dimes = 0L;
		long nickels = 0L;
		long pennies = 0L;
		
		// Divide remaining currency by currency values and cast to whole number
		// Remainder stored back into remaining currency.
		dollars = (long) (currencyValue / 100.0);
		currencyValue = (currencyValue % 100.0);
		
		quarters = (long) (currencyValue / 25.0);
		currencyValue = (currencyValue % 25.0);
		
		dimes = (long) (currencyValue / 10.0);
		currencyValue = (currencyValue % 10.0);
		
		nickels = (long) (currencyValue / 5.0);
		currencyValue = (currencyValue % 5.0);
	
		// All that is left is pennies after all other units subtracted out.
		pennies = (long)currencyValue;
        
		System.out.printf("The currency %.2f makes %d dollars, %d quarters, %d dimes, %d nickles and %d penniesn", currency, dollars, quarters, dimes, nickels, pennies);
		
}

Submitted: October 23, 2012

Return to the snippets listing