Cash Register help needed!

Cash Register help needed!
0

#1

Tell us what’s happening:
Hi everyone,

I almost passed this project but I think one test case keeps failing… I think this is because of floating calculation in java script… I believe the problem lies in line 15 where I calculate floating points… Can anyone help me to solve this issue of floating point calculation?

Your code so far


function checkCashRegister(price, cash, cid) {
  var change = [];
  var changeDue = cash-price;

  if(changeDue>cid.reduce((sum,cid)=>sum+cid[1],0)){
    return {status: "INSUFFICIENT_FUNDS", change: []};
  } else if(changeDue===cid.reduce((sum,cid)=>sum+cid[1],0)){
    return {status: "CLOSED", change: [...cid]};
  } else {
    for(let i=cid.length-1; i>=0; i--){
      if(changeDue >= cid[i][1]){
        change.push(cid[i])
        changeDue-= cid[i][1]
      } else if(Math.floor(changeDue/changeVal[cid[i][0]]>1)){
        change.push([cid[i][0], changeVal[cid[i][0]]*Math.floor(changeDue/changeVal[cid[i][0]])])
        changeDue-= (changeVal[cid[i][0]])*(Math.floor(changeDue/changeVal[cid[i][0]]))
      }
    }
    if(changeDue!==0){
      return {status: "INSUFFICIENT_FUNDS", change: []}
    } else {
      return {status: "OPEN", change: [...change]}
    }
  }
}

var changeVal = {
  "ONE HUNDRED": 100,
  "TWENTY": 20,
  "TEN": 10,
  "FIVE": 5,
  "ONE": 1,
  "QUARTER": 0.25,
  "DIME": 0.1,
  "NICKEL": 0.05,
  "PENNY": 0.01
}

// Example cash-in-drawer array:
// [["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", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])["change"])

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register


#2

You can use a combination of parseFloat and toFixed methods. Also, debugger is your friend when you have a bug like that.


#3

@ RadoIIvanov
Thanks for your comment. I added the following code at the line 16 and now it works. I think this is a bit different with what you’ve suggested. but works.

changeDue = Math.round(changeDue*100)/100