Click here to Skip to main content
14,272,331 members
Rate this:
Please Sign up or sign in to vote.
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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

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.
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

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.
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

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[^]
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100