Unexpected Javascript Result

I am doing a calculation in a java script, but I ran into a problem due to decimal precision. I can’t post the exact calculation, but this is what I am doing, which leads to an unexpected result.

When I write: alert(100.01-36.01);// the result is 64

But when I write: alert(100.01-37.01);// the result is 63.00000000000001

and this continues as for 38.01 .... so on. Can someone help me why this shows such unexpected behavior. I'm stuck in the calculation.

Thanks in advance.

+5
source share
2 answers

Try the following:

<script type = "text / javascript">
var n1 = parseFloat (100.01);
var n2 = parseFloat (37.01);
var res = (n1-n2)
alert (res.toFixed (2));
</script>
+1

, js , .

parseFloat (123.45) .

0

All Articles