Math returns not correct
this is a fragment of code that fails me:
let n = Math.floor(change / cashValues[i]);
// if cid hasn't got enough bills
while (n * cashValues[i] > a[1]) {
n--; // n - -; just for visual clarity in forum
}
let takeAway = n * cashValues[i]
console.log(`${change} - ${takeAway}`)
console.log(change - takeAway)
so the problem is :
console.log(`${change} - ${takeAway}`)
returns 96.74 and 60 as it should, how ever:
console.log(change - takeAway)
returns 36.739999999999995 and I am almost sure that it should result in 36.74.
Could anyone point out what is going on here?
OK I got a deeper problem, while waiting for replies I decided to take CID array and sum it’s values and it resulted in same busted math: 335.40999999999997
function checkCashRegister(price, cash, cid) {
let bank = cid.map(i => i[1]).reduce((a,b) => a + b);
console.log(bank);
}
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]])
this is all what is in the function and it still returns incorrect math.
Floating point numbers (decimal) in computers hand rounding. There are many ways to account for this. Personally, I like using an integer number of cents.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.