0

Why does javascript returns so many zeros and not just 0.24 And how can i disable javascript to do this. Because when im using a calculator i never get the result 0.24000000000002

var sum = (0.0001 * 2400);

result 0.2400000000002

Alex.U
  • 1,631
  • 2
  • 16
  • 26
Tan
  • 2,148
  • 3
  • 33
  • 54
  • 4
    `(0.0001 * 2400).toFixed(2)` – Tushar Oct 22 '15 at 09:06
  • but i dont want fixed 2 because sometimes if the result is reallt 0.258 i want it to be 0.258 and not 0.25800000000004 example – Tan Oct 22 '15 at 09:07
  • 1
    reference: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Yoshi Oct 22 '15 at 09:07
  • What about math.round() ? – B001ᛦ Oct 22 '15 at 09:08
  • what about console.log(0.0001 * 2400 / 10); ? – Oleksandr T. Oct 22 '15 at 09:08
  • @Yoshi I strongly believe that I know enough about floating-point arithmetics, but this article looks awfully difficult for me - so much math, theorems, formulas. I think it will be too confusing for a user who knows nothing about it. – Yeldar Kurmangaliyev Oct 22 '15 at 09:09
  • @YeldarKurmangaliyev On a first glance it very much looks like such. But it actually issn't all that complicated. It's even understandable if one would just skip the crazy formulas. :) – Yoshi Oct 22 '15 at 09:12

2 Answers2

1

The reason for this is that your sum is a float which are known to not be very precise. This is a limitation of float values.

To fix this you need to round the decimals by either Math.round or .toFixed.

Daniel
  • 3,726
  • 4
  • 26
  • 49
0

javascript always do that but you can make it show only 2 digits after the dot.

var sum = (0.0001 * 2400);
alert(sum.toFixed(2));
David Pankov
  • 105
  • 1
  • 10