0

I have a problem with add negative numbers jquery, code:

var k = parseFloat(-0.1) + parseFloat(0.3);
console.log(k); // 0.19999999999999998

but i need results 0.2

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Also see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Alex K. Apr 15 '17 at 17:49

1 Answers1

1

This has to do with how computer's parse numbers, specifically the floating point representation. 0.1 is 1/10 which cannot be exactly represented by a number of base 2 (i.e. 2^n).

If you can accept some rounding error I would refer you to this answer, and do something like this:

var k = parseFloat(-0.1) + parseFloat(0.3);

k = Math.round(k * 100) / 100; // 2 decimal points precision. Use 10 instead of 100 for 1 decimal point precision.
console.log(k); // 0.2 :)

Hope this helps.

Community
  • 1
  • 1
ant0nisk
  • 581
  • 1
  • 4
  • 17