Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I improve this algorithm?
    text
    copied!<p>What I am trying to accomplish is to take a US Currency amount, and break it down into how many of each bill and coin it takes to make that amount using the least of each type.</p> <p>I wrote this in a hurry, and it works, but I feel like it could be improved. Also, I had to round the remainder because I was getting a strange result once it got to something like (0.13 - (1 * 0.1) instead of 0.3 it would come out to 0.299999995</p> <p>The code below does seem to work.</p> <pre><code>function moneybreak ($amount, $sizebill) { // get units of sizecurrency $numbills = floor($amount / $sizebill); $remainder = $amount - ($numbills * $sizebill); $remainder = round($remainder, 2); $ret['bills'] = $numbills; $ret['remain'] = $remainder; return $ret; } $amount = 1999.99; $money = array(); $tmoney = moneybreak($amount, 500); $money['fivehundred'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 100); $money['onehundred'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 20); $money['twenty'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 10); $money['ten'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 5); $money['five'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 1); $money['one'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 0.25); $money['quarter'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 0.1); $money['dime'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 0.05); $money['nickle'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; $tmoney = moneybreak($tmoney['remain'], 0.01); $money['penny'] = ($tmoney['bills'] &gt; 0) ? $tmoney['bills'] : 0.00; </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