0

The following code leads my game app to a strange behavior! I tried the same code In some modern languages such as Java C# and here is the JavaScript version!

   var x = .3 - .2,
       y = .2 - .1,
       areEqual= (x == y),
       xIsDotOne = x == .1,
       yIsDotOne = y== .1;

areEqual is false, xIsDotOne is false but yIsDotOne is true.

So how to let them return the exact value?

Bellash
  • 7,560
  • 6
  • 53
  • 86
  • 3
    You can't; compare with a margin of error. Welcome to floating-point numbers. – ssube Mar 17 '15 at 14:54
  • Floating point number precision http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Venkata Krishna Mar 17 '15 at 14:54
  • 1
    Read [this](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – juharr Mar 17 '15 at 14:56
  • FWIW: Double in C#/Java and numbers in JavaScript use the same underlying representation (64-bit IEEE 754 'doubles'). I would expect them all to have the same result for this particular case. – user2864740 Mar 17 '15 at 15:00
  • [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – user2864740 Mar 17 '15 at 15:03
  • Agree with welcome to jungle with floats, but answering your question... `yIsDotOne == .1` is not a valid expression that's why different results. If you do: `yIsDotOne = y == .1` you will get false as expected... – Jordi Castilla Mar 17 '15 at 15:07
  • @JordiCastilla typing mistake... `yIsDotOne = y == .1;` – Bellash Mar 18 '15 at 08:03

0 Answers0