Bad addition using reduce

I have this code so far and i’m getting availableChange = 335.40999999999997

I fixed it by adding toFixed(2) at the end of the recude method but I don’t understand why is that happening. The b[1] values seem to be okey but theres a problem with the acc.

function checkCashRegister(price, cash, cid) {
const 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 change = cash-price;
let availableChange = cid.reduce((a,b) => {
  return a + b[1];  
},0)/*.toFixed(2)*/;
console.log(availableChange);
return change;
}

checkCashRegister(19.5, 20, [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
]
);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

Challenge: Cash Register

Link to the challenge:

This isn’t because of reduce. This is the co-called floating-point error, due to how float numbers are represented internally performing calculations using them can be inaccurate.

For example try:

console.log(0.1 + 0.1 + 0.1 == 0.3)
1 Like

I’m searching and I can’t find a normalized way to deal with it. Then, should I let the code like that if it works?
Thank you.

One approach, to minimize number of places where error might affect calculations, would be making sure as many calculations as possible in function are done on integers, and only at the last step the result is going back to floats.

But if something else is working and giving enough precision, then it should be okay too.

1 Like