We help IT Professionals succeed at work.

# parseFloat : Why do I get the wrong answer

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)
}
}

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

## View Solution Only

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
</script>

Working on it..

Commented:
try this:

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

Commented:
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...

Commented:
or even this:

total += 100 * e.value / 100;

... if you want two decimal places ... use 1000 for 3, etc.

Commented:
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

Commented:
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

Commented:
yes, if the string begins with 0 ...

parseFloat("09");

then base 8 (octal) is assumed

Commented:
but my example makes no sense ... how about parseFloat("012");

Commented:
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

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!!