Cash Register project - Interesting error

Hello guys, here is my code for this task/project. I don’t pass 3rd and 6th test because my code is making some mathematical rounding error (as i can tell) in while loop. As you are going to see, problem occurs with pennies. Here is the code:


function checkCashRegister(price, cash, cid) {
  let arr = [0.01,0.05,0.1,0.25,1,5,10,20,100];
  let a = cash-price, arrReal =[], RealSum = 0, arr2=[];
  let arr3 = ["ONE HUNDRED","TWENTY","TEN","FIVE","ONE","QUARTER","DIME","NICKEL","PENNY"]
  //finding number of particular coins and total sum in cid
  for (let i=cid.length-1;i>=0;i--){
    let sum = Math.round(cid[i][1]/arr[i]);
    arrReal.push(sum);
    RealSum +=sum*arr[i];
  }

  let obj = new Object();
  obj.change = [];
  arr.reverse();
  let cidSum = 0;
   // error/mistake is probably here in while loop
  for (let j=0;j<9;j++){
    let sum = 0;
    while (arrReal[j]>0 && a>=arr[j]){
      sum++;
      a-=arr[j];
      arrReal[j]--;
    }
    arr2.push(arr[j]*sum);
      if (arr2[j]>0){
        obj.change.push([arr3[j],arr2[j]]);
        cidSum+=arr2[j];
      }
  }
  a = cash-price;
  if (a === RealSum){
    obj.status = "CLOSED"
    return obj;
  } else if (a>RealSum || a!==cidSum){         
    obj.status = "INSUFFICIENT_FUNDS";      
    obj.change = [];    // delete this line and
    return obj;         // change this line into "return obj.change;" to see error
  } else {
    obj.status = "OPEN"
    return obj;
  }
}

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]]) )

when u change the above mention lines, you’ll get this as result:
TWENTY,60,TEN,20,FIVE,15,ONE,1,QUARTER,0.5,DIME,0.2,PENNY,0.03
but PENNY should be 0.04

Why is that mistake there and how to fix it?
Thanks

I think you will find this video interesting, and will explain your issue:

1 Like