Just Only One Penny Less - Cash Register

After hours of coding, everything is fine but this code calculates one penny less and I cant find whats going wrong.


function checkCashRegister(price, cash, cid) {
const ChangeCash = {
  "PENNY": .01,
  "NICKEL": .05,
  "DIME": .10,
  "QUARTER": .25,
  "ONE": 1.00,
  "FIVE": 5.00,
  "TEN": 10.00,
  "TWENTY": 20.00,
  "ONE HUNDRED": 100.00
}
let change = cash - price;
let resultArr = [];
let totalValue = 0;
for(let i of cid){
  totalValue += i[1]
}
totalValue = totalValue.toFixed(2)
if(change > totalValue){
  return {status: "INSUFFICIENT_FUNDS", change: []}
} else if(change == totalValue){
  return {status: "CLOSED", change: cid}
} else {
  for(let j = cid.length - 1; j >= 0; j--){
    let element = cid[j]
    let amount = 0;
    let newArr = []
    if(ChangeCash[element[0]] < change){
      if(element[1] > change){
        amount = (Math.floor(change / ChangeCash[element[0]])) * ChangeCash[element[0]];
        change -= amount;
        newArr.push(element[0]);
        newArr.push(amount)
        resultArr.push(newArr)
      } else {
        amount = element[1];
        change -= amount;
        newArr.push(element[0]);
        newArr.push(amount)
        resultArr.push(newArr)
      }
    } else {
      continue;
    }
  }
            console.log(resultArr)
  if(change > 0){
    return {status: "INSUFFICIENT_FUNDS", change: []}
  } else {
    return {status: "OPEN", change: resultArr}
  }
}
}

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

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

Challenge: Cash Register

Link to the challenge:

Hi @nisanurcontay34 ,

Limit the decimals for ‘change’ variable, wherever it is modified:

change = change.toFixed(2)

@manjupillai16 I blurred the code just to keep it spoiler-free.

@nisanurcontay34 Try logging out change after the change -= amount; operation. As said, you can solve it using toFixed. I would suggest you keep the value of type number though.

In place:

change = Number((change - amount).toFixed(2));

Thank you so much @manjupillai16 and @lasjorg . It worked eventually.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.