-1

in javascript.

<script>
    alert(10.99*11);// = 120.89
    alert(11.99*11);// = 131.89000000000001
    alert(12.99*11);// = 142.89000000000001
    alert(13.99*11);// = 153.89000000000001
    alert(14.99*11);// = 164.89000000000001
    alert(15.99*11);// = 175.89000000000001
    alert(16.99*11);// = 186.89
</script>

Why is this?

Why returns 000000000001?

  • I'm guessing it's to do with floating-point calculations. – GarethL Mar 21 '14 at 10:07
  • maybe you should consider take a look at this, Java have similar problem, since basically, data is binary http://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library – sujoe Mar 21 '14 at 10:10

1 Answers1

0

11.99 does not have an exact representation in binary floating point so the compiler used the closest possible value to it. So when you multiply by 11 you get an answer that's really really close to the value you wanted but not exactly right.

This happens with other values. For example...

data = 0.3

What value does data contain? Hint : It's not 0.3 because 0.3 cannot be exactly represented in floating point, it might be 0.299999999999999988897769753748434595763683319091796875 which is the closest value representable in one particular floating point binary format. it's very very close but not identical. The same issue applied to your numbers.

jcoder
  • 29,554
  • 19
  • 87
  • 130