Cash Register Challenge puzzle

Hi all,
I’m working on the Cash Register challenge and starting with the hard part: figuring out the change breakdown when the total amount of cid is greater than the change required. I have an algorithm that looks like it starts off well but then does something very strange. Here’s my code so far:

function checkCashRegister(price, cash, cid) {
  let values = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
  let change = cash - price;
  let changeArr = [];
  for (let i=cid.length -1; i>= 0; i--) {
    if (values[i] <= change && cid[i][1] > 0) {
      let subArr = [];
      subArr.push(cid[i][0]);
      let amount = 0;
      while (amount <= change) {
        amount += values[i];
        change -= values[i];
      }
      subArr.push(amount);
      changeArr.push(subArr);
    }
  }
  console.log(changeArr);
}

checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

When I run this I get the right amount for the twenties and tens but then inexplicably it stops at 10 for the fives, even though I’m pretty confident that according to my code it should go ahead and put 15 from the fives in there, since the change would still be 16.74 which is greater than 15:

[ [ 'TWENTY', 60 ],
  [ 'TEN', 20 ],
  [ 'FIVE', 10 ],
  [ 'ONE', 4 ],
  [ 'QUARTER', 1.5 ],
  [ 'DIME', 0.7 ],
  [ 'NICKEL', 0.3 ],
  [ 'PENNY', 0.11999999999999998 ] ]

…any thoughts on why this strange behavior is happening? For now I’m not so concerned about the floating point inaccuracy as it seems to only show up at the penny stage.

Thanks,
JD

Update: figured it out! First problem was I was using the wrong condition in while, which would make it stop prematurely before adding up the right about. The second issue was the standard decimal problem in Javascript arithmetic, which I solved by using cents throughout instead of at the end. Here’s the new algorithm:

function checkCashRegister(price, cash, cid) {
  let values = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];
  let change = cash*100 - price*100;
  let changeArr = [];
  for (let i=cid.length -1; i>= 0; i--) {
    console.log(change)
    if (values[i] <= change && cid[i][1] >= 0) {
      let subArr = [];
      subArr.push(cid[i][0]);
      let amount = 0;
      while (values[i] <= change && amount < (cid[i][1]*100)) {
          amount += values[i];
          change -= values[i];
      } 
      subArr.push(amount/100);
      changeArr.push(subArr);
    }
  }
  console.log(changeArr);
}

checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

This one gives exactly the right answer.