Tell us what’s happening:
So I guess its a floating point issue? How do I fix my code to rectify the issue?
because i cosole logged the change:
0.009999999999994869
0.009999999999999691
Your code so far
function checkCashRegister(price, cash, cid) {
let currency={
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100
}
let totalInCid = 0;
for(let element in cid){
totalInCid += cid[element][1];
}
totalInCid = totalInCid.toFixed(2);
let change = cash - price;
let changeArr = [];
if(change > totalInCid){
return {status: "INSUFFICIENT_FUNDS", change: changeArr};
} else if(change === totalInCid){
return {status: "CLOSED", change: cid};
}else{
cid = cid.reverse();
for(let element of cid){
let denominationName = element[0];
let denomitionChangeTotal = 0;
while(change >= currency[element[0]] && element[1] > 0){
denomitionChangeTotal += currency[denominationName];
change -= currency[denominationName];
element[1] -= currency[denominationName];
}
denomitionChangeTotal = Number(denomitionChangeTotal.toFixed(2));
let temp = [denominationName, denomitionChangeTotal];
if(denomitionChangeTotal > 0){
changeArr.push(temp);
}
}
}
console.log(change);
if (change !== 0) {
return { status: "INSUFFICIENT_FUNDS", change: []};
}
return { status: "OPEN", change: changeArr};
}
console.log(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]]));
console.log(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/108.0.0.0 Safari/537.36
Challenge: JavaScript Algorithms and Data Structures Projects - Cash Register
Link to the challenge: