3

I have a fiddle here: http://jsfiddle.net/94wQJ/1/ - but probably someone can advise just by looking below.

<button type="button" id="allocate">Calc</button>

 $('#allocate').click(function () {
     val1 = 25.00;
     val2 = 16.37;
     val3 = val1-val2;
     alert(val3);
 });

25 - 16.37 = 8.63 - however, the alert for val3 = 8.62999999999

Why is it not accurate?

Thank you,

Mark

Mark
  • 7,778
  • 24
  • 89
  • 147
  • 1
    some good info here http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – andy mccullough Sep 27 '13 at 08:31
  • elaborate discussion here http://stackoverflow.com/questions/11832914/round-up-to-2-decimal-places-in-javascript and here http://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript – hima Sep 27 '13 at 08:38

4 Answers4

5

Try Using toFixed more information here

val3.toFixed(2)

Demo Fiddle

Community
  • 1
  • 1
Greenhorn
  • 1,690
  • 11
  • 12
  • Thank you Ram, I'll mark as the answer as soon as SO allows. Strange behaviour!! Cheers, Mark – Mark Sep 27 '13 at 08:31
  • 1
    @MarkTait - It is not strange behaviour - It is due to the limitations (known) of floating point numbers – Ed Heal Sep 27 '13 at 08:51
3

Why is it not accurate?

This is a duplicate of Is floating point math broken?, but to answer your specific question: floating point numbers generally store the number in base 2 because it allows storing more numbers more accurately than using base 10, at the expense of not being able to exactly store all base 10 numbers even with a small number of decimal places.

Community
  • 1
  • 1
Douglas
  • 36,802
  • 9
  • 76
  • 89
  • its not just Javascript's floating point math - it's floating point math in general unless you use things like specialised Decimal classes. – sevenseacat Sep 27 '13 at 09:08
  • @sevenseacat: yes, agreed. You could go further and say that it is a limitation on how much information can you store in a particular number of bits, I can't quote which bit of information theory would apply though. – Douglas Sep 27 '13 at 09:11
1

Many decimal fractions not be represented exactly in binary.

Use .toFixed(2)

PSR
  • 39,804
  • 41
  • 111
  • 151
1

Please check this

val3 = Math.round(val3*100)/100;

I have update here http://jsfiddle.net/94wQJ/7/

hima
  • 610
  • 3
  • 10
  • 24