# forEach vs. for in javascript does not come out the same

2

This is a JavaScript exercise that you can find on the following page:

This is my code:

``````function checkCashRegister(price, cash, cid) {
debugger;
var toReturn = cash - price;
var cashArray = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
var counter = 0;
var total = 0;
var result = {
status: "",
change: [["ONE HUNDRED", 0], ["TWENTY", 0], ["TEN", 0], ["FIVE", 0], ["DOLLAR", 0], ["QUARTER", 0], ["DIME", 0], ["NICKEL", 0], ["PENNY", 0]]
}

total = cid.reduce(function(acc,val){
return (acc * 100 + val[1] * 100) / 100;
},0);

if(total < toReturn){
result.status = "INSUFFICIENT_FUNDS";
result.change = [];
return result;
} else if(total == toReturn){
result.status = "CLOSED";
result.change = cid;
return result;
} else {
result.status = "OPEN";

cid.forEach ( function (i, a){
while([i][0][1] > 0 && toReturn - cashArray[a] >= 0){
[i][0][1] = Math.round(([i][0][1] - cashArray[a]) * 100) / 100;
result.change[counter][1] += cashArray[a];
toReturn = toReturn - cashArray[a];
var b = Math.round(toReturn * 100);
toReturn = b / 100;
}
counter++;
})

/*for(var i = cid.length - 1; i >= 0; i--){
while(cid[i][1] > 0 && toReturn - cashArray[i] >= 0){
cid[i][1] = cid[i][1] - cashArray[i];
result.change[counter][1] += cashArray[i];
toReturn = toReturn - cashArray[i];
var b = Math.round(toReturn * 100);
toReturn = b / 100;
}
counter++
}
}*/
if (toReturn != 0){
result.status = "INSUFFICIENT_FUNDS";
result.change = [];
return result;
}
var filtered = result.change.filter(function(x){
return x[1] > 0;
});
result.change = filtered;
return result;
}

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

My question is in the part of forEach and the For that is commented on in the code. The FOR if I get what I want, but instead, the forEach gives me 0.50000000000002 (approximately), and I do not get 0.5. I have tried using Math.round (), toFixed (2), etc. but none results.

Could someone explain to me why it is that I get different in this case? Any other suggestions to accelerate the exercise? Improve your efficiency?

edit. My goal is that the program runs well.

asked by Max 18.08.2018 в 18:12
source