We help IT Professionals succeed at work.

parseFloat : Why do I get the wrong answer

pjbcoetzer
pjbcoetzer asked
on
I am trying to calculate a total of dynamically created text boxes. I am getting the wrong values when I use the “parseFloat” function.

The Code:
~~~~~~~~~

var f = document.forms.item("frmCalculate")
  var total = 0;
   
  for (var i = 0; i < f.length; i++)
  {
    var e = f.elements(i)
    if (e.name == "Per_Value")
    {
      total += parseFloat(e.value)
      alert(total)  //Testing
    }
  }
  alert(total)  //Testing

The Values:
~~~~~~~~~~~
   1.  62.84
   2.  32.43
   3.  4.73

The result:
~~~~~~~~~~~
   100.00000000000001

I know the result should be 100, but why is it not??

Comment
Watch Question

Commented:
Amazing ! it has nothing to do with parseFloat

Look at this :

<script language="vbscript">
dim num1,num2,num3
num1 = 62.84
num2 = 32.43
num3 = 4.73
msgBox (num1+num2+num3)
</script>

<script language="javascript">
var num1,num2,num3
num1 = 62.84
num2 = 32.43
num3 = 4.73
alert (num1+num2+num3)
</script>



Working on it..
try this:

total += Math.round(parseFloat(e.value)*100)/100;
oops

total += Math.round(parseFloat(e.value*100)/100);

Commented:
knightEknight, you are right, it will solve the problem, but any ideas about the origin of it ? it's a very simple floating numbers addition...
or even this:

total += 100 * e.value / 100;

... if you want two decimal places ... use 1000 for 3, etc.
no clues as to why this happens ... but I have seen it before.

Commented:
using a JavaScript 1.5 solution :

var num1,num2,num3
num1 = 62.84
num2 = 32.43
num3 = 4.73
alert (new Number(num1+num2+num3).toLocaleString())


my last post was an error ... it should be:

total += Math.round(100*e.value)/100;
Top Expert 2005

Commented:
ONe related issue:

When using parseFloat() and parseInt(), it is best to pass the radix as the second parameter, i.e., parseFloat('12',10). For some historical reason that I cannot recall at the moment, if you do not pass the second parameter, an 8 is assumed and that can cause some wierdness in calculations.

Fritz the Blank
yes, if the string begins with 0 ...

  parseFloat("09");

then base 8 (octal) is assumed
but my example makes no sense ... how about parseFloat("012");

Commented:
I haven't found any notes about this second parameter, I belive it's deprecated.
Top Expert 2005

Commented:
Avner, I believe that you are right! The parseInt() method does take the second parameter, see http://developer.netscape.com/docs/manuals/communicator/jsref/glob15.htm#1012508, but the parseFloat() doesn't appear to.

Good to learn something new!


Fritz the Blank

Author

Commented:
I still don't know why Java Script does this, but the code supplied did the trick.

I hope SUN knows of this and fix the problem...

Thanks!!