Exiting out of the loop for my cash register

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

Hello,

When I run my code, it gives me one less penny than the change needed.  Is my loop closing before adding the counter? 


Thank you 

function checkCashRegister(price, cash, cid) {
  
  const money =  [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", .1], ["QUARTER", 0.25],["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]]  
  
  let Ans ={
    status:"",
    change:[]
  };
  let coins = 0;
  let changeNeeded = cash-price;
  console.log(changeNeeded)
  let totCoins = []
  for(let h =0; h<= 8; h++){
    totCoins.push(Math.round(cid[h][1]/money[h][1]))
  }
  let float = 0
  for(let m=0; m<8; m++){
    float = float + money[m][1]*totCoins[m]
  }
  if(float-changeNeeded > 0){
    Ans.status ="OPEN"
  } else if(float - changeNeeded === 0){
    Ans.status ="CLOSED"
  } else if(float < changeNeeded){
    Ans.status ="INSUFFICIENT_FUNDS"
  }
  console.log(float)

if(Ans.status !== "INSUFFICIENT_FUNDS"){
  // this loop goes through each coin to see how which ones can give the correct amount of change
  for(let i = 8; i>=0; i--){
    for(let j= money[i][1]; j<=changeNeeded; j = j+money[i][1]){
      if(j<=changeNeeded && coins <totCoins[i]){
      coins++  
      }
    }
    // alters the change to be passed back into the loop
    if(money[i][1]*coins !== 0){
    Ans.change.push([money[i][0],money[i][1]*coins])
    }
    changeNeeded = changeNeeded- money[i][1]*coins
    coins = 0
    
  }
  }
  console.log(Ans.change.length)
   let changeTot = 0
   for(let n =0; n<Ans.change.length; n++){
     changeTot = changeTot + Ans.change[n][1]
   }
   if(Math.round(changeNeeded) !== 0| changeTot <changeNeeded){
    Ans.status = "INSUFFICIENT_FUNDS"
    Ans.change =[]
   }
  console.log(Ans)
  return Ans; 
}

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/90.0.4430.85 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

Floats don’t work very well when translated to binary so things get messed up along the way and you get weird results, but JS has a way to work with this and that would be:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Or:

//to round down
let val = 3.7778
Math.floor(val  * 100) / 100
//output: 3.77
//to round up
let val = 3.7778
Math.ceil(val  * 100) / 100
//output: 3.78

The last two methods should work regardless of language.

thank you very much.

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