Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parseFloat function

Status
Not open for further replies.

alpha23

Programmer
Joined
Jul 12, 2004
Messages
1
Location
US
Hello everyone,

I have a javascript function with the following code in one of my ASPs. I have a set of fields, and that is what the for loop is for. I enter values in either all or some of the fields in this set. The for loop here adds all those values and returns the total. The problem is that when I have the following set of values, 8.51, 0, 10.00.....my total turns out to be 18.50 and not 18.51.

To figure out what the issue was, I put an alert statement after everytime the total is done(I have 3 fields in this case). I found that the total after first looping is 8.51, after second is 8.51 and total after the third and the final looping is 18.5099999999998.

If I remove the parseFloat function, and add just the values, I get the right answer. What is wrong with parseFloast function? Any help would be appreciated.

for (i=0; i<=totalfields-1;i++)
{

j = "txt_Fee_" + sABNCode + "_" + i;
k = "txt_PatResponsibility_"+ sABNCode + "_" + i;

if (!eval("document.CheckCodes." + j + ".disabled")){
if (eval("document.CheckCodes." + k + ".value") != "**" )
{
x = eval("document.CheckCodes." + k + ".value");
if (eval("document.CheckCodes." + k + ".value")== "")
{
x = 0;
}
else
{
x=x.replace(",", "");
}
total += parseFloat(x.valueOf());
alert('tot='+ total);
}
}
}

Thank you in advance.
 
The question of "why" is always a good one. I hope someone has the answer. I also hope no one tries to send a rocket to Mars based on JavaScript's parseFloat() function!

If you want to make sure to get your two-decimal answer, try this after you finish setting total:

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

--Dave
 
> I also hope no one tries to send a rocket to Mars based on JavaScript's parseFloat() function!

No problem... launch it, then rename it to Pioneer XIII, Voyager 3 or something.

Theoretically speaking, divide 4 by 7 and take as many decimals you want. Number is never 100% accurate. Same applies for "computer version" of 8.51 because it uses 2-base notation (javascript uses 64-bit IEEE-754). Numbers like 0.01 have infinite number of decimals in binary form and data loss appears. Some languages muffle this at higher levels, Javascript obviously doesn't.

More info to check:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top