JavaScript Algorithms and Data Structures Projects - Cash Register

Tell us what’s happening:
So I guess its a floating point issue? How do I fix my code to rectify the issue?

because i cosole logged the change:
0.009999999999994869
0.009999999999999691
Your code so far

function checkCashRegister(price, cash, cid) {
  let currency={
    "PENNY": 0.01,
    "NICKEL": 0.05,
    "DIME": 0.1,
    "QUARTER": 0.25,
    "ONE": 1,
    "FIVE": 5,
    "TEN": 10,
    "TWENTY": 20,
    "ONE HUNDRED": 100
  }

  let totalInCid = 0;
  for(let element in cid){
    totalInCid += cid[element][1];
  }
  totalInCid = totalInCid.toFixed(2);


  let change = cash - price;
  let changeArr = [];

  if(change > totalInCid){
    return {status: "INSUFFICIENT_FUNDS", change: changeArr};
  } else if(change === totalInCid){
    return {status: "CLOSED", change: cid};
  }else{
    cid = cid.reverse();
    for(let element of cid){
      let denominationName = element[0];
      let denomitionChangeTotal = 0;
      while(change >= currency[element[0]] && element[1] > 0){
        denomitionChangeTotal += currency[denominationName];
        change -= currency[denominationName];
        element[1] -= currency[denominationName];
      }
      denomitionChangeTotal = Number(denomitionChangeTotal.toFixed(2));
      let temp = [denominationName, denomitionChangeTotal];
      if(denomitionChangeTotal > 0){
        changeArr.push(temp);
      }
    }
  }

console.log(change);
  
  if (change !== 0) {
    return { status: "INSUFFICIENT_FUNDS", change: []};
  }

  return { status: "OPEN", change: changeArr};
}



console.log(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]]));
console.log(checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: JavaScript Algorithms and Data Structures Projects - Cash Register

Link to the challenge:

There is a well known issue with math with floating point numbers.

In base 10, any fraction with a denominator that is a multiple of only 2s and 5s can be represented perfectly - nothing else will. Try to accurately represent 1/3 or 1/5 or 1/127 in a decimal - it can’t be done.

In base 2, any fraction with a denominator that is a multiple of only 2s (exponent of 2) can be represented perfectly. Nothing else can. Type .1 + .2 into your console. That is 1/10 and 1/5 - the computer cannot accurately represent those without an infinite number of digits so they are approximations.

To fix this, you either need to use a library to handle these, do some intelligent rounding, or convert everything to cents so you can deal with integers.