Tell us what’s happening:
Could someone please help me and explain what is happening?
When you paste the code into the console, without the parseFloat(change.toFixed(2)); on the 35.line, I dont know why, but in the while loop, as I substract, the numbers happen to not be rounded well, they are wrong by about 0,0000001 ±.
Your code so far
var total = 0; // all cash in register
var change = cash - price; //how much supposed to return
var arrChange = []; //new arr, output
var j;
var n = 0; // number of notes/ coins of same value that will be returned
var arrValue = [ 0.01, 0.5, 0.1, 0.25, 1.00, 5.00, 10.00, 20.00, 100];//create arr of values
for(var l in cid){
cid[l].push(arrValue[l]);//asign given values
cid[l].push(cid[l][1]/cid[l][2]);//asign how many coins/notes there are of given values
}
//all cash in registry
for(var i in cid){
total += cid[i][1];
}
//check if enough money
if(total<cash - price){
return "Insufficient Funds";
}else if(total == cash - price){
return "Closed";
}
j = cid.length - 1; // go trough cid from the end, (bigest values to smallest)
while(change!=0 && j >= 0){
if(change >= cid[j][2] && cid[j][3]>0){ // if I value is smaller, and I have it at least 1
n = 1;
while((n+1)*cid[j][2] <= change && n <cid[j][3]){ //return it as many times
n++;
}
console.log(change);
change -= n*cid[j][2];
console.log(change);
change = parseFloat(change.toFixed(2)); // problem here
arrChange.push([cid[j][0], n*cid[j][2]]);
}
j--;
}
//i i had money but not the right combination to return
if(change === 0){
return arrChange;
}else{
return "Insufficient Funds";
}
}
checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36.
Link to the challenge:
https://www.freecodecamp.org/challenges/exact-change