0

Right now I'm working on a ledger-type program in a web application. I'm using angularJS to handle the events, but it's raw Javascript that handles the actual calculation

var onEntriesSuccess = function(data) {
    var sum = 0;
    var isDebit = ($scope.account.active == "D" ? true : false);
    angular.forEach(data, function(value, key){
        sum += (isDebit ? value.debit - value.credit : value.credit - value.debit);
        value.balance = sum;
    });

    $scope.entries = data;
}

Which seems to work fine; however, while running it against my test case I find that it fails because when the sum = 10496.82 and attempts to subtract 6912.00 it comes out with

3584.8199999999997

I've never encountered an error like this before, at first I thought it was floating point and switched the value from 6912.02 to 6912.00. However, that doesn't seem to fix anything. Could anyone please explain this? Thanks

Yogeshree Koyani
  • 1,649
  • 10
  • 19
Jujunol
  • 457
  • 5
  • 18
  • can you make a fiddle ? – J Santosh Oct 13 '15 at 04:16
  • 2
    No need for a fiddle, this is caused due to floating point number system javascript uses: http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Saar Oct 13 '15 at 04:17
  • you can easily reproduce it by doing `0.1+0.2 == 0.3` which will result in false as the actual result of `0.1+0.2` in JS will be 0.3000...4 again this is due to the Number system JS uses – Saar Oct 13 '15 at 04:19
  • 1
    consider using `value.balance = Math.round(sum * 100) / 100;` (==3584.82) probably the best workaround for this kind of floating point "weirdness" in javascript. – davidkonrad Oct 13 '15 at 04:28
  • Fiddle : [link](http://jsfiddle.net/t4r8aqck/) True that does make sense if it were subtracting a decimal value instead of just 6912.00. If I make modifications so that the numbers yield 8496.82 - 912.00 then there's no floating point :/ – Jujunol Oct 13 '15 at 04:40
  • @Jujunol - yes :) `(Math.round(parseFloat(num) * 100) / 100).toFixed(2)` see **https://jsfiddle.net/z18pmfkq/** for various examples. – davidkonrad Oct 13 '15 at 04:54

1 Answers1

1

I updated Your fiddle

Live Link

sum=parseFloat(sum.toPrecision(16))

I take this solution from:

Stack overflow Answer

Community
  • 1
  • 1
Arunkumar
  • 5,150
  • 4
  • 28
  • 40