was doing an algorithm question, and my code produced unexpected output. heres the code
const price = 3.26;
const cash = 100;
const cid = [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
];
function checkCashRegister(price, cash, cid) {
let change = cash - price;
let totalInReg = 0;
for (let i = 0; i < cid.length; i++) {
totalInReg += cid[i][1];
}
if (totalInReg < change) {
const output = {
status: "INSUFFICIENT_FUNDS",
change: []
};
console.log(output);
}
const coins = {
'PENNY': 0.01,
'NICKEL': 0.05,
'DIME': 0.1,
'QUARTER': 0.25,
'ONE': 1,
'FIVE': 5,
'TEN': 10,
'TWENTY': 20,
'ONE HUNDRED': 100
}
const outputArr = [];
for (let i = cid.length - 1; i >= 0; i--) {
const coinType = cid[i][0];
let coinReg = cid[i][1];
const coinValue = coins[coinType];
const infoArr = [];
if (coins[coinType] > change) continue;
let currCoinCt = 0;
do {
coinReg -= coinValue;
change -= coinValue;
/* change = parseFloat(change.toPrecision(4)); */
console.log(change)
currCoinCt++;
} while (coinReg > 0 && change >= coinValue)
infoArr.push(coinType);
infoArr.push(currCoinCt * coinValue);
outputArr.push(infoArr);
}
}
was expecting it to subtract the coin values, which only had 2 decimal places max. but the output i get in the console is:
76.74
56.739999999999995
36.739999999999995
26.739999999999995
16.739999999999995
11.739999999999995
6.739999999999995
1.7399999999999949
0.7399999999999949
0.4899999999999949
0.23999999999999488
0.13999999999999488
0.03999999999999487
0.02999999999999487
0.01999999999999487
0.009999999999994869
with use of toPrecision and parseFloat, i was able to remedy my problem. but why is this happening? is this a javascript thing? i am using an online editor on 'jsfiddle.net'. thanks in advance