1

Possible Duplicate:
Is JavaScript's Math broken?
Strange result with floating point addition

Some simple JavaScript calculations in Safari 5.0.6 but the same phenomenon in Firefox:

var i=0.1;
i=i+0.01;       //= 0.11
i=i+0.01;       //= 0.12
i=i+0.01;       //= 0.13
i=i+0.01;       //= 0.14
i=i+0.01;       // expected == 0.15
console.log(i); // == 0.15000000000000002

Where does this imprecision come from?

Sure, I can handle it with i.toPrecision() or other methods, but does it have to be like that? Is this a floating-point rounding error?

The same happens in this example:

var i=0.14+0.01; //expected == 0.15
console.log(i);  //== 0.15000000000000002

What is happening between 0.14 and 0.15?

var i=0.1400001+0.01; //expected==0.1500001
console.log(i);       //== 0.1500001 ok!

and

var i=0.14000001+0.01; //expected==0.15000001 !! 
console.log(i);        //== 0.15000001000000002

What do I have to do differently to get the correct results?

Community
  • 1
  • 1
frank
  • 81
  • 7
  • 5
    Welcome to the world of representing floating point numbers in binary. – wkl Dec 22 '11 at 05:41
  • http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html so it is a problem made by storing the data to calculate in bits 'n bites? – frank Dec 22 '11 at 05:42
  • 1
    You can reproduce a similar effect more concisely with `0.1 + 0.2`, which results in `0.30000000000000004`. – Peter Olson Dec 22 '11 at 05:43
  • Alex has a good link, but essentially it is because binary cannot represent all floating points from base10. 0.1 is actually one such number you can't represent correctly in binary. – wkl Dec 22 '11 at 05:46
  • @birryree It's not related to binary. It's just that you only have a very little amount of information that you can store. Whether that is decimal or binary or whatever makes no matter. – phant0m Sep 20 '12 at 12:04
  • Me: `0.1 + 0.2 == 0.3` Javascript: `false` – Maverick Mar 21 '14 at 02:59

3 Answers3

8

Floating Point Arithmetic is not precise, as some numbers can not be accurately stored so an approximation is used.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Can you handle your Numbers as integers and then work out the final answer with division?

alex
  • 479,566
  • 201
  • 878
  • 984
0

They're just floating point errors.

Work with integers, multiply everything you're doing by 10 * numbers of precision you want.

Jessedc
  • 12,320
  • 3
  • 50
  • 63
0

Floatinhg point numbers are stored not precisely in computers - you need to take into account their binary representation. Hence with floating point number arithmetic you get rounding errors.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127