Using reduce but getting an answer a few decimals short of correct one?

Using reduce but getting an answer a few decimals short of correct one?
0.0 0

#1

Hi everyone,
working on cash register project, I encountered the following quirk: when I sum all the values in the new array I created with the numbers in each element of the cid array, I get a weird result:

function checkCashRegister(price, cash, cid) {
  var change;
  var arrSum = [];
    cid.forEach(function (element) {
      arrSum.push(element[1]);
    });
    console.log(arrSum); **// [1.01, 2.05, 3.1, 4.25, 90, 55, 20, 60, 100]**
    var newArrSum = arrSum.reduce(function (acc, val) {
      return acc + val;
    });
    console.log(newArrSum); **// 335.40999999999997**
  }

The result should be 335.41, but I’m getting only a few decimals short of that. Why does this happen and how can I fix it?

Thanks!!!


#2

This is not a bug per se. This is a feature of JavaScript that has to do with the way floats are encoded. Here is a link that explains why this happens and offers a(n imperfect) solution : http://adripofjavascript.com/blog/drips/avoiding-problems-with-decimal-math-in-javascript.html


#3

That’s how computers do floating-point numbers, and JS only has floating-point numbers.

As a non-computer based comparison:

10 ÷ 3 = 3.333333…

then

3.333333… + 3.33333… + 3.3333333… = 9.9999999…

(there are ways to explain this behaviour and fix it, but the same principle applies to floating-point maths. And computers can’t say “this is a recurring number” and deal with it accordingly, because they can’t tell.)