I’m doing the last javascript project, but got in trouble with floating point number, I tried to fix it with .toFixed(2) but it still is, off by 0.01.
Here is the code
function checkCashRegister(price, cash, cid) {
//check total cash in draw
const totalCID = () => {
let acc = 0;
cid.forEach(each => acc += each[1])
return Number(acc.toFixed(2));
};
//console.log(totalCID())
//check change amount
let changeDue = cash - price;
//determine status
const checkStatus = () => {
return changeDue > totalCID()
? "INSUFFICIENT_FUNDS"
: changeDue < totalCID()
? "OPEN"
: "CLOSED"
};
//making an array/object to store our change
let change = []; //for storing numbers according to bill/coin
let changeReturn = []
//making arrays that help determine which bill and coins we will use for the the change
const changeCount = [100, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01];
let cashInDraw = cid.reverse();
//making change return system
for (let i = 0; i < changeCount.length; i++){
while (changeDue >= changeCount[i]){
if (cashInDraw[i][1] < changeCount[i]){
break;
};
change.push(changeCount[i])
changeDue -= changeCount[i];
cashInDraw[i][1] -= changeCount[i];
}
//push change(bill/coins) and its value accordingly
if (change.length !== 0){
let acc = 0
change.forEach(each => acc += each)
changeReturn.push([cashInDraw[i][0], Number(acc.toFixed(2))]);
change = [];
}
}
//console.log(changeReturn)
//assemple our check that include status and change
let check = {}
check.status = checkStatus();
check.change = changeReturn;
//console.log(check);
//console.log(cashInDraw)
return check;
}
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]])
Here is the Output:
{ status: 'OPEN',
change:
[ [ 'TWENTY', 60 ],
[ 'TEN', 20 ],
[ 'FIVE', 15 ],
[ 'ONE', 1 ],
[ 'QUARTER', 0.5 ],
[ 'DIME', 0.2 ],
[ 'PENNY', 0.03 ] ] }
Notice the PENNY is paired with 0.03, but it should be 0.04.
So, what can I do to fix this problem. Any suggests will be appreciate, Thanks you.