0

When I create a loop to subtract .1 from a variable with a value of 1, the output after a few rounds results in a long float point number with extra digits at the end. Why am I getting the following results instead of the results that should be expected?

var x = 1;
for (var y = 0; y < 10; y++) {
    x-=.1; 
    console.log(x);
}

And the result giving by the console output:

0.9

0.8

0.7000000000000001

0.6000000000000001

0.5000000000000001

0.40000000000000013

0.30000000000000016

0.20000000000000015

0.10000000000000014

1.3877787807814457e-16

However when I substract .3 from 1 the console output gives me the expected .7 value. Is this a browser specific issue with JavaScript implementation?

Community
  • 1
  • 1
Konstantin
  • 42
  • 1
  • 11
  • Here is the fiddle http://jsfiddle.net/3xNFc/ it's funny when you do `0.8-0.1` in console, you get the 0.70000001 – Huangism Jul 31 '14 at 15:21

2 Answers2

0

That is a rounding error. You have that in every language when calculating with floating point numbers. If you want the correct number you have to round.

Take a look at the chapter Rounding Error on this page http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Praind
  • 1,551
  • 1
  • 12
  • 25
  • Yeah. I solved my rounding error by Math.round(10*x)/10 But I've never run into this problem before. I want to know why it occurs. – Konstantin Jul 31 '14 at 15:26
  • Take a look here at the Rounding Error chapter. http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Praind Jul 31 '14 at 15:28
0
var x = 10;
for (var y = 0; y < 10; y++) {
    x-=1; 
    console.log(Math.round(x)/10);
}
Flip Vernooij
  • 889
  • 6
  • 15
  • As far as I know, TS is strugling with a rounding error. The above very simple and small modification to his code solves that problem. Elaborate,.. floating points are a pain for sure this is true in javascript. So try to make your calculations before the '.', by multipling the base by 10/100/1000 or whatever. then make your calculation and divide it again. Financial applications and databases are doing the same with their currency values, they are multiplied by a 1000 to make sure (almost) no rounding errors ocure. – Flip Vernooij Aug 01 '14 at 08:59