Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your question is a perfect example of <a href="https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency/3730040#3730040">why you shouldn't use floating-point arithmetic to represent currency</a>.</p> <p>First, you'll need to avoid floating-point numbers like you owe them a lot of money (though actually it might be the opposite). To that end, we'll do our calculations with cents instead of dollars. Any amount you might have needs to be multiplied by 100.</p> <p>You can then rather easily get away by listing all the money units you want to use ($100, $50, $20, ...) into an array, and sort it in descending order so the biggest ones come out first.</p> <pre><code>&lt;?php // money units, in cents // (reflecting common Canadian currency) $units = array(10000, 5000, 2000, 1000, 500, 200, 100, 25, 10, 5, 1); function moneyBreak($amount, $units) { // ensure the array is sorted in descending order rsort($units); $itemsOfEach = array(); // loop through all the money units foreach ($units as $unit) { // you'll try to use this money unit for the largest possible // amount of money $itemsOfEach[$unit] = intval($amount / $unit); // and once you're done, you'll continue with the remainder $amount %= $unit; } return $itemsOfEach; } ?&gt; </code></pre> <p>And here is an example:</p> <pre><code>$amount = 32347; // $323.47 $result = moneyBreak($amount, $units); print_r($result); /* prints this: Array ( [10000] =&gt; 3 [5000] =&gt; 0 [2000] =&gt; 1 [1000] =&gt; 0 [500] =&gt; 0 [200] =&gt; 1 [100] =&gt; 1 [25] =&gt; 1 [10] =&gt; 2 [5] =&gt; 0 [1] =&gt; 2 ) */ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload