Javascript Arithmetic Error [duplicate]

1

Today I went through a strange problem, a simple calculation of the sum of the difference according to the ordering.

If in the browser console perform this calculation below:

2.3+2.3+2.1

The expected value would be 6.7 correct? Yeah, but from 6.699999999999999, so far so good, it's understandable ....

But .. if I change the order of the values, putting the lower one first.

2.1+2.3+2.3

Surprise "mothafoca"! 6.7

Note: I can not use toFixed because I do not want to lease this number, where you can correct a problem now, but it will result in something worse up front.

A fucking solution that went through my head but I refuse to use it would be.

soma = 0;
[2.3, 2.3, 2.1].sort().forEach( valor => {
   soma += valor
});
    
asked by anonymous 09.12.2016 / 14:55

1 answer

2

The arithmetic of fractional numbers is never exact (at least for non-multiple numbers of 1/2 powers). The exact solution was pure coincidence.

One way to resolve the issue is to convert the problem into integer arithmetic (or fixed point, not available in Javascript).

So assuming you always use a decimal place, the sum would be:

   23+21+23 = 67 // Exato!

Still, by showing the result, 67/10 could result in something like 6.7000001 or 6.999999 ...

    
09.12.2016 / 15:02