Help please, with exact change challenge

Help please, with exact change challenge
0

#1

I’m losing my mind! For the solution that is supposed to return 96.74, my solution is ONE PENNY SHORT and I can not seem to figure out the issue. Please help.


#2

sorry, forgot to include the code!

function checkCashRegister(price, cash, cid) {
  var changeGiven = [];
  var money = [0.01, 0.05, 0.10, 0.25, 1.00, 5.00, 10.00, 20.00, 100.00].reverse();
  var changeDue = cash - price;
  var sum = cid.reduce(function(a, b) {
    return a + b[1];
  }, 0);
  sum = Math.round(sum * 100) / 100;
  cid.reverse();
  
  
  if (changeDue > sum) {
    return "Insufficient Funds";
  }
  
  else if (changeDue == sum) {
    return "Closed";
  }
for (var i  = 0; i < cid.length; i++) {
  var value = 0;
  while (cid[i][1] > 0 && money[i] <= changeDue) {
    changeDue -= money[i];
    cid[i][1] -= money[i];
    value += money[i];
    
  }
  value  = Math.round(value * 100) / 100;
  
  if (value > 0) {
    changeGiven.push([cid[i][0], value ]);
  }
  
} return changeGiven;
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);

#3

You are running into trouble with javascript rounding decimals and floating point numbers. When your loop is being evaluated, it thinks that changeDue == 96.739999999999 which eventually gets rounded off to 96.73, and thus you are a penny short.

I can give you an idea about how to resolve that particular issue if you want, but just to let you know your solution is also unable to deal with situations where there is more than enough cash in the register, but it is not in denominations suitable for handing out change (i.e., if the change due is 0.03, but the only thing that is in the cash register is $100 bills.


#4

Thank you! After googling some about my issue, I saw similar answers, so I ~should~ be able to figure out the solution to deal with the decimals. Also, I’m not done with the code! I tend to work piece by piece, and was trying to fix that part before moving on, but thank you so much!


#5

Cool, yeah, I figured you were gonna work on that part later, but I wanted to mention it just in case anyway.

Best of luck solving the issue! Floating point numbers are one of my most hated things to deal with.