2

PFB an example code snippet illustrating the issue:

        var x=0.323;
        var cumulativeVal = 0;

        for(i=0;i<30;i++){
                   cumulativeVal = cumulativeVal + x;
                   console.log(cumulativeVal);
        }

The result of the above computation is

  0.323
  0.646
  0.9690000000000001
  1.292
  1.615....
  4.845000000000001
  5.168000000000001
  5.491000000000001
  5.814000000000002....
  9.690000000000007

Note that an extra decimal value is getting added. I do understand that this has something to do with precision of values in javascript. But can anyone explain?

Raghav
  • 1,014
  • 2
  • 16
  • 34
  • 1
    Check http://stackoverflow.com/questions/1907114/integers-and-float-precision for an good answer on how floats are stored. – zrvan Jan 16 '12 at 22:40
  • possible duplicate of [Is JavaScript's Math broken?](http://stackoverflow.com/questions/588004/is-javascripts-math-broken) – Ivo Wetzel Jan 16 '12 at 22:43

1 Answers1

4

There's nothing particular to explain. IEEE-754 double-precision numbers are not completely, perfectly precise in decimal terms. Small errors can creep in. For full decimal precision (which, you should note, cannot perfectly represent one-third) you'd need to use a type designed for that. (JavaScript doesn't have one built in; examples from other languages would be BigDecimal from Java, or decimal from C#.)

There's an easier example, by the way:

0.1 + 0.2 = 0.30000000000000004

It's one of Crockford's favorites.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875