Cash register Challenge - strange result when using for..in loop on array

Hi, I’m currently on the cash register challenge and ran into a weird occurrence using a for…in loop on the default array.

When using the loop to add every item of the array to find the total cash in drawer it gives an odd long decimal result when none of the input values got beyond the thousandth. All values added together equal to 335.41 but i’m getting 335.40999999999997. could someone explain what’s going on.

Thanks for any help.

function checkCashRegister(price, cash, cid) {
  let cashInDrawer = 0;
  for (let denom in cid) {
    cashInDrawer+= cid[denom][1];
  }

  console.log(cashInDrawer)
}

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

335.40999999999997

edit : I’m getting the same result for other loops too

for(let i = 0; i < cid.length; i++) {
    cashInDrawer+= cid[i][1];
  }

  cid.forEach(denom => {cashInDrawer += denom[1]});

When Javascript turns your decimal say 0.3 into binary, it becomes an unending fraction 0.333333... This is due to the number format JS uses, and it happens with a few other programming languages to that use the same format (Java, C, Ruby, etc).

You can read more about it here.

From my experience the best thing to do is to round sums before you compare them. You can do this with the .toFixed() method in JS.

Hopefully this helps!

Thanks! this code works now

function checkCashRegister(price, cash, cid) {
  let cashInDrawer = 0;

  cid.forEach(denom => {cashInDrawer += denom[1]});
  
  cashInDrawer = cashInDrawer.toFixed(2);
  console.log(cashInDrawer)
}

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