Cash Register : why is sum 335.409999997?

Cash Register : why is sum 335.409999997?
0

#1

Tell us what’s happening:
I wrote a reducer to calculate the total amount in the cash register. I’m getting 335.4099999997, when it should be 335.41. Why does it sum up like this?

Your code so far


function checkCashRegister(price, cash, cid) {
  var change = {
    status: "INSUFFICIENT_FUNDS",
    change: []
  };
  
  if (cash < price) {
    return change;
  }
  //Sum cid
  const reducer = (accumulator, curVal) =>  accumulator + curVal[1];
  let total = cid.reduce(reducer, 0);
  console.log(total);

  return change;
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]

let chg = 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]]);

console.log(chg["status"]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:63.0) Gecko/20100101 Firefox/63.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register


#2

To debug this, I might expand your fat arrow function:

  const reducer = (accumulator, curVal) =>  {
    console.log(accumulator, curVal);
    return accumulator + curVal[1];
  }

Doing this, the console will show you the problem happens at the second addition. Simplest workaround? Force the number to round to two digits:

  const reducer = (accumulator, curVal) =>  Number(parseFloat(accumulator + curVal[1]).toFixed(2) );

It’s a hacky solution, but floating point math can be.


#3

Long answer: What every JavaScript Devleoper Should Know About Floating Point Numbers

Short answer: Computers don’t deal with decimals well and you get rounding errors.