Javascript unexpected result

I am doing an calculation in java script but i am facing a problem due to precision in decimal numbers. I can not 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); // result is 64

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

and it goes on like this for on. Can any please help me to why this is showing such an unexpected behavior. I am stuck in a calculation.

Thanks in advance.


Try this :

<script type="text/javascript">
var n1 = parseFloat(100.01);
var n2 = parseFloat(37.01);
var res = (n1-n2)

if you do not declare the numbers as numbers, js will automatic use it as string, if the string is not only used by numbers.

parseFloat(123.45) will set it as decimal number.

Need Your Help

cn1 - replace background image

css background-image codenameone

I have a button on which I set the background image using css, and then sometimes need to change it dynamically in the code. But if I change it, I see both images, one on top of the other.

javascript not reading characters

php javascript string variables

I'm sure the answer to this is stunningly simple - but I can't find it!