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
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
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.