-1

What kind of mistakes? How do I fix this?

1.1 - 1 = 0.10000000000000009

1.0000001+1 = 2.0000001000000003

iajrz
  • 749
  • 7
  • 16
lukaszpolowczyk
  • 605
  • 1
  • 7
  • 27
  • 7
    Welcome to the world of IEEE 754 arithmetic. :-) – RobG Nov 07 '13 at 02:54
  • 4
    This is not an error, but a fact of life with floating point arithmetic. See [What every programmer should know...](http://floating-point-gui.de/) –  Nov 07 '13 at 02:56
  • This is actually the correct answer. Check out http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Gene Nov 07 '13 at 03:01

3 Answers3

4

you can solve this by using .toFixed() method
its the floating point problem take a look here

eg:

<script>
alert((1.234567890).toFixed(2))
</script>
Community
  • 1
  • 1
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
0

The javascript uses the data type float. Float numbers are never exact so do not use == when you compare the data instead use < and/or >.

Icy Creature
  • 1,875
  • 2
  • 28
  • 53
  • 1
    Floating point numbers can be exact, just not for all decimal values within their range. – RobG Nov 07 '13 at 03:01
  • Still, inequality comparisons don't solve the problem (floating point error will still affect the result), unless you add a check for an arbitrary "epsilon". – Qantas 94 Heavy Nov 07 '13 at 04:13
0

From the comp.lang.javascript FAQ(which seem to be down at the moment):

ECMAScript numbers are represented in binary as IEEE-754 (IEC 559) Doubles, with a resolution of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to just over 9e15 are precise, but few decimal fractions are. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.

In particular, non-integer results should not normally be compared for equality, and non-integer computed results commonly need rounding.

RobG
  • 142,382
  • 31
  • 172
  • 209