Skip to content

Instantly share code, notes, and snippets.

@mgkimsal
Created April 22, 2009 22:34
Show Gist options
  • Save mgkimsal/100137 to your computer and use it in GitHub Desktop.
Save mgkimsal/100137 to your computer and use it in GitHub Desktop.
<?php
class Coinage {
public $amount;
private $_values = array();
public $values = array();
public function __construct() {
$this->_values = array(
'fifties'=>'5000',
'twenties'=>'2000',
'tens'=>'1000',
'fives'=>'500',
'ones'=>'100',
'quarters'=>'25',
'dimes'=>'10',
'nickels'=>'5',
'pennies'=>'1'
);
}
/**
* given a dollar amount (12.47 for example)
* calculate the smallest amount of change possible
* value is held internally, ready to be displayed
* via displaySmallestChange()
* @see displaySmallestChange
* @param Float Floating point dollar amount (12.47, 9.74, etc)
*/
public function determineSmallestChange($amount) {
$amount = $amount * 100;
$initialAmount = $amount;
foreach($this->_values as $currency=>$pennies) {
$temp = floor($amount/$pennies);
$amount -= ($temp * $pennies);
$this->values[$currency] = $temp;
}
}
/**
* display the smallest amount of change calculated by
* determineSmallestChange() method
*
* return String HTML
*/
public function displaySmallestChange() {
$output = '';
foreach($this->values as $currency=>$number) {
if((int)$number>0) {
$output .= "there would be $number $currency\n";
}
}
return $output;
}
}
$start = microtime(true);
$value = 12.47;
$c = new Coinage();
$c->determineSmallestChange($value);
echo "For ".money_format("\$%i", $value).", the smallest amount of change is:\n";
echo $c->displaySmallestChange();
$time = microtime(true) - $start;
echo "\nThis took $time time\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment