5

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 38.01....so on. Can any please help me to why this is showing such an unexpected behavior. I am stuck in a calculation.

Thanks in advance.

Sovan Misra
  • 109
  • 1
  • 1
  • 3
  • 2
    Machines don't have infinite precision, so one must always be careful when comparing floating point values, 64 is a special number for a machine, its a power of 2 so it can represent it quite well. – Samy Vilar Jun 20 '12 at 06:18
  • 1
    this might help you http://stackoverflow.com/questions/588004/is-javascripts-math-broken – Samy Vilar Jun 20 '12 at 06:24
  • 2
    This has been asked at least a million times on SO, please use the search before posting a question. – Niko Jun 20 '12 at 06:28
  • I checked, it's actually been asked a billion times. – phenomnomnominal Jun 20 '12 at 06:48

2 Answers2

1

Try this :

<script type="text/javascript">
var n1 = parseFloat(100.01);
var n2 = parseFloat(37.01);
var res = (n1-n2)
alert(res.toFixed(2));
</script>
Ravinder Singh
  • 3,113
  • 6
  • 30
  • 46
0

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.