Skip to main content
Commonmark migration
Source Link

##Spend a penny get a warning.

Spend a penny get a warning.

###The common approch

The common approch

##Spend a penny get a warning.

###The common approch

Spend a penny get a warning.

The common approch

Source Link
Blindman67
  • 22.3k
  • 2
  • 16
  • 40

##Spend a penny get a warning.

Just for fun a warning not a rigorous answer

###The common approch

Many places have a different system than have removed the smaller coins for convenience. Thus there is a need to round the change to the nearest coin value before doing the calculation. Also you would do the calculation in the actual unit eg dollars not cents, and you don't give counts of coins, you tally and give the total. Eg not "2 tens" but "20 in tens"

The following calculates change in $ rounding to the nearest lowest coin and does not work, the logic is sound just the number system that cant. The function will display a warning if it can not balance the books.

When dealing with indivisible units using division, be careful.

function getChange(sum) {
  var coins = [100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05];
  var coinIndex = 0;
  sum = Number((Math.round(sum / coins[coins.length - 1]) * coins[coins.length - 1]).toFixed(2));
  log("Change for $" + sum.toFixed(2));
  log("-----------------------------");
  while (sum > 0 && coinIndex < coins.length) {
    const value = coins[coinIndex++];
    const coinChange = Number((Math.floor(sum / value) * value).toFixed(2));

    if (coinChange) {
      log("$" + coinChange + " in $" + value.toFixed(2))
    }

    sum -= coinChange;
  }
  if(sum > 0){ 
      log("-----------------------------");
      log("Balance $"+sum);
      log("WARNING WARNING rounding error. What are you doing using doubles for cash!!!!!!"); 
  }

}

function log(str) {
  if (str === undefined) {
    till.innerHTML = "";
    return;
  }
  var div = document.createElement("div");
  div.textContent = str;
  till.appendChild(div);
}


function randSpend() {
  log(); // clear;
  getChange(Math.random() * 1000);
  log("-----------------------------");
  log("Click to spend more. :) ");
};
document.body.addEventListener("click", randSpend);
randSpend();
<div id="till"></div>