Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am using VC++ 6.0 and having following problem with the atof().

char test[10];
strcpy(test,"1.003");
float flTest=atof(test);
double dbTest=atof(test);

Now flTest returns 1.003, but dbTest returns 1.00299999. Anyone advice why this is happening and not getting the correct conversion?

Thanks
Neil
Posted
Updated 23-Apr-10 1:39am
v2

This this because binary numbers cannot represent all possible real numbers. So when you specify a real number which cannot be represented then its nearest real number is used.

-Saurabh
 
Share this answer
 
This is really not an issue.
It's just the way floating point numbers are represented.

When you say returns, you're actually doing a printf here.
So if printf("%f", dbTest); returns 1.00299999, check what printf("%.3f", dbTest); returns.
 
Share this answer
 
As Saurabh said:

This this because binary numbers cannot represent all possible real numbers. So when you specify a real number which cannot be represented then its nearest real number is used.


Just another thing: there cannot exist two overloads of a functions that differ only by the return value. This means that on your code snippet, you are always calling the function double atof(const char *buffer), and the compiler implicitly casts the returned value to float. This means that there is nothing strange under the hood with double arithmetic and atof function, as Adam Roderick J erroneusly asserted.
 
Share this answer
 
v2
I have noticed this issue with swprinf in VS 2008, and then i dig the reason behind it.
And i found that last bit is having lose with the data in last bit, which is lost in arithmetic of double operations. I believe atof is having some sort of arithmetic that is creating the loss.
So a solution such problem is what i was looking and i found it in codeproject in the below mentioned article:- Five Tips for Floating Point Programming[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900