Hey y’all,
This is my first post on the forums. I thought I figured out how to solve floating points by just multiplying my numbers in the beginning by 100 and dividing by 100 at the end. That seemed to work for each item on the checklist except for the last one. The PENNY value is 5 with a repeating decimal when it should just be 5. Does anyone see something I’m missing? Or is there a better way to deal with floating points?
function checkCashRegister(price, cash, cid) {
/* removes value from remainder, cid, and adds value to used array*/
var valArr = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000]
var remainder = (cash - price)*100;
var used = [["PENNY", 0],["NICKEL", 0],["DIME", 0],["QUARTER", 0],["ONE", 0],["FIVE", 0],["TEN", 0],["TWENTY", 0],["ONE HUNDRED", 0]]
cid.map(obj => obj[1] = obj[1]*100)
for (let i = valArr.length - 1; i >= 0; i--) {
while(valArr[i] <= remainder && cid[i][1] > 0) {
remainder -= valArr[i];
cid[i][1] -= valArr[i];
used[i][1] += valArr[i]/100;
}
}
/* reshifts the used array */
var newUsed = [];
used.map(obj => newUsed.unshift(obj))
var result = {
status: "",
change: ""
}
/* checks remainder for results*/
if(remainder == 0) {
result.status = "OPEN"
result.change = newUsed.filter(obj => !obj.includes(0))
} else {
result.status = "INSUFFICIENT_FUNDS";
result.change = [];
}
return result;
}
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]]));
/* result */
{ status: 'OPEN', change: [ [ 'PENNY', 0.5000000000000002 ] ] }