Errors in Cash Register

Hi! I don’t know why I’m getting results with a lot of decimals if I’m not using any different value from the one in the “cid”. This is causing errors in the case 3 and 6. I tried everything but nothing is working.

function checkCashRegister(price, cash, cid) {
  
  let totalCurrency = 0;
  let difference = cash - price;
  let change = {
    status: "",
    change: []
  }
  const currencyChecker = (currency) => {
    switch(currency) {
      case "PENNY":
        return 0.01;
        break;
      case "NICKEL":
        return 0.05;
        break;
      case "DIME":
        return 0.1;
        break;
      case "QUARTER":
        return 0.25;
        break;
      case "ONE":
        return 1;
        break;
      case "FIVE":
        return 5;
        break;
      case "TEN":
        return 10;
        break;
      case "TWENTY":
        return 20;
        break;
      case "ONE HUNDRED":
        return 100;
        break;
    }
  }
  let tempChange = 0;

  for(let currency of cid) {
    totalCurrency += currency[1];
  }

  for(let i = cid.length - 1; i >= 0; i--) {
    if((difference/currencyChecker(cid[i][0])) >= 1) {
      let finalCurrencyAm = 0;
      while((tempChange + currencyChecker(cid[i][0])) <= difference
            && cid[i][1] > 0){
          tempChange += currencyChecker(cid[i][0]);
          cid[i][1] -= currencyChecker(cid[i][0]);
          finalCurrencyAm += currencyChecker(cid[i][0]);
      }
      if(finalCurrencyAm !== 0) {
        change.status = "OPEN";
        change.change.push([cid[i][0], finalCurrencyAm]);
      }
    }
  }

  if (tempChange !== difference) {
    change.status = "INSUFFICIENT_FUNDS";
    change.change = [];
  }else if(totalCurrency === difference) {
    change.status = "CLOSED";
    change.change = [...cid];
  }
  console.log(tempChange);
  return change;
}

Thanks a lot for the help guys!

For example this is the last case, the one that should give “CLOSED” but… the result doesn’t make sense. There is no way to get 0.490000000000… if I use just the values into the cid array.

There is a rounding issue somewhere which is caused by JavaScript.
check this topic for a good explanation.

Thanks a lot! I got it. :grinning:

The rounding issue has nothing to do with JavaScript. The rounding issue is inherent in how computers store decimal numbers.

Thanks for correcting me, somehow I related it to JavaScript.

No worries. I just wanted to make sure that you are on the lookout for it with other languages too.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.