0

I have a table in which I sum up values starting with zero.

Some values I am getting are wrong. I'm using .toFixed(2) to show the results to the user.

I've used console.log to see internally the sums:

> 0 - 70 = -70
> -70 + 1182 = 1112
> 1112 - 970 = 142
> 142 - 900 = -758
> -758 - 300 = -1058
> -1058 - 210 = -1268
> -1268 - 150 = -1418
> -1418 - 150 = -1568
> -1568 - 40 = -1608
> -1608 + 1182 = -426
> -426 - 450 = -876
> -876 - 39.6 = -915.6
> -915.6 + 1182 = 266.4
> 266.4 - 39.6 = 226.79999999999998
      // the problem starts here to down
> 226.79999999999998 - 226.79 = 0.009999999999990905
> 0.009999999999990905 - 100 = -99.99000000000001
> -99.99000000000001 + 99.99 = -1.4210854715202004e-14
    // this is the most crazy: '$ -99.99' plus '$ 99.99' gives '$ -1.42'
> -1.4210854715202004e-14 + 1.42 = 1.4199999999999857

How can I workaround this situation?


@Bergi. My code:

$http.get('/app/php/planData.php').success(function(data){
    for (var i=0, l=data.length; i<l; i++) {
        var out = data[i].out;
        var before = parseFloat(i ? data[i - 1].subtotal : 0);
        var cash = parseFloat(data[i].cash);
        data[i].subtotal = out ? before - cash : before + cash;
        console.log(before + (out? ' - ' : ' + ') + cash + ' = ' + data[i].subtotal);
    }
    $scope.dataPlan = data;
    loading('off');
}).error(function(){ console.log('Error searching Plan data.'); });

html:

<span style="color: {{mov.subtotal < 0 ? '#f00' : 
(mov.subtotal > 0 ? '#00f' : '#000')}}" 
ng-bind="mov.subtotal | mymoney"></span>

filter:

appModule.filter('mymoney', function () {
    return function (input) {
        return input && ('$ ' + String(input).match(/^\-?\d+(?:\.\d\d?)?/)[0]);
    };
});

1 Answers1

2

this is the most crazy: '$ -99.99' plus '$ 99.99' gives '$ -1.42'

That's not true, the result you're getting is:

-1.4210854715202004e-14

which is close to:

0.00000000000001421085...

(see the negative exponent)

To avoid floating point issues, try rounding the sums before using them further. It's happening because of the way floats are stored in memory - there are tons of online resources on that topic if you're interested in learning it in more detail.

Shomz
  • 37,421
  • 4
  • 57
  • 85