Hello people. I am struggling to understand why my code doesn’t work:
It does work except in this case
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]]) should return {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}.
I really don’t understand why but instead of putting into the array [“PENNY”,0.04] the While stops at 0.03. Please help me.
function checkCashRegister(price, cash, cid) {
///////////Change to give///////////
var change = cash - price;
var changeToGive = [];
///////////////////////////////////////
/////////////////////Total///////////////////////
var total = 0;
for(var i = 0; i<cid.length; i++){
if(cid[i][1]>0){
total += cid[i][1];
}
}
total = total.toFixed(2);
////////////////////////////////////////////////
//////////////Give change/////////////////
if(total>change){
var changeInHand = 0;
for(var i = 8; i!=-1; i--){
if(cid[i][1]>0){
var amount = 0
while(cid[i][1]>0.0001){
if(cid[i][0]=="ONE HUNDRED" && (changeInHand+100)<=change){
changeInHand+=100;
amount+=100;
cid[i][1]-=100;
total-=100;
}else if(cid[i][0]=="TWENTY" && (changeInHand+20)<=change){
changeInHand+=20;
amount+=20;
cid[i][1]-=20;
total-=20;
}else if(cid[i][0]=="TEN" && (changeInHand+10)<=change){
changeInHand+=10;
amount+=10;
cid[i][1]-=10;
total-=10;
}else if(cid[i][0]=="FIVE" && (changeInHand+5)<=change){
changeInHand+=5;
amount+=5;
cid[i][1]-=5;
total-=5;
}else if(cid[i][0]=="ONE" && (changeInHand+1)<=change){
changeInHand+=1;
amount+=1;
cid[i][1]-=1;
total-=1;
}else if(cid[i][0]=="QUARTER" && (changeInHand+0.25)<=change){
changeInHand+=0.25;
amount+=0.25;
cid[i][1]-=0.25;
total-=0.25;
}else if(cid[i][0]=="DIME" && (changeInHand+0.1)<=change){
changeInHand+=0.1;
amount+=0.1;
cid[i][1]-=0.1;
total-=0.1;
}else if(cid[i][0]=="NICKEL" && (changeInHand+0.05)<=change){
changeInHand+=0.05;
amount+=0.05;
cid[i][1]-=0.05;
total-=0.05;
}else if(cid[i][0]=="PENNY" && (changeInHand+0.01)<=change){
changeInHand+=0.01;
amount+=0.01;
cid[i][1]-=0.01;
total-=0.01;
}else{
break;
}
}
}
if(amount!=0){
changeToGive.push([cid[i][0],amount]);
}
}
alert(changeToGive)
if(changeInHand!=change){
return {status: "INSUFFICIENT_FUNDS", change: []}
}else if(change==changeInHand){
return {status: "OPEN", change:changeToGive}
}
}else if(change>total) {
return {status: "INSUFFICIENT_FUNDS", change: []}
}else if(total == change) {
return {status: "CLOSED", change:cid}
}
//////////////////////////////////////////
}
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]])