473,387 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Why doesn't atof work?

Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}
Jul 22 '05 #1
10 4771

"Drew" <pe*****@bellsouth.net> wrote in message news:JS*******************@bignews5.bellsouth.net. ..
//Why does this store 3.099999905 in fNum

Because that is the closest representable number (3.1 is almost surely not exactly
representable in binary) after it's been converted back to decimal for printing.
Jul 22 '05 #2
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}

What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.

Jul 22 '05 #3
Thank you for the great responces.
This was the first time I had ever been to this group.
Lots of smart people here!

One more question:
How can you save some floats to a text file and read them back acurately?

Thank you.
Best regards,

Drew

"Jeff Schwab" <je******@comcast.net> wrote in message
news:nd********************@comcast.com...
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}

What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.

Jul 22 '05 #4
Thank you all for the great responces.
This was the first time I had ever tried this group.
Lots of smart people here!

If I may, one last question?
Suppose you wanted to write your floats to a text file and read them back
exactly, how would you do it?

Thank you.

Drew


"Jeff Schwab" <je******@comcast.net> wrote in message
news:nd********************@comcast.com...
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}

What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.

Jul 22 '05 #5
On Tue, 20 Jan 2004 16:28:57 -0600 in comp.lang.c++, "Drew"
<pe*****@bellsouth.net> was alleged to have written:
I'm having trouble getting atof() to accurately convert "3.1"


The usual answer to that is the same in C++ as it is in C, and is
covered in Steve Summit's C FAQ. See the topic "14.1: When I set a
float variable to, say, 3.1, why is printf printing it as 3.0999999?"
It is always good to check the FAQ before posting. You can get the FAQ
at:
http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #6
Drew wrote:

One more question:
How can you save some floats to a text file and read them back acurately?


Well, this method is probably not recommended, but it
will get you the EXACT same value, provided you read
in on the same architecture it was printed from.

Print the float using a HEX format with enough digits
to cover the entire variable. Then read it back in
using the same HEX format. What you're doing in this
case is effectively printing the exact BIT representation
of the number using HEX notation. When you read it in
the same way, you reproduce the same bit pattern. THEN
looking at it as a float it will be the same as before.

NOTE: I have not tried this in C/C++, but have done it
in other languages. I'm not sure exactly what you might
have to do (casts/etc) to make the Read step work right.
Play with it awhile and see what you get. If you get
it working, post it here so others can see it. :)

Mike
Jul 22 '05 #7
Depends on the level of precision required. Presuming 1 decimal place:

write:

fprintf(file, "%.1f\n", float_value);

read:

fscanf(file, "%f\n", &float_value);
Drew wrote:

Thank you for the great responces.
This was the first time I had ever been to this group.
Lots of smart people here!

One more question:
How can you save some floats to a text file and read them back acurately?

Thank you.
Best regards,

Drew

"Jeff Schwab" <je******@comcast.net> wrote in message
news:nd********************@comcast.com...
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}

What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.


--
Bret Pehrson
mailto:br**@infowest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl>>
Jul 22 '05 #8
Drew wrote:
Thank you all for the great responces.
This was the first time I had ever tried this group.
Lots of smart people here!

If I may, one last question?
Suppose you wanted to write your floats to a text file and read them back
exactly, how would you do it?

Thank you.

Drew


"Jeff Schwab" <je******@comcast.net> wrote in message
news:nd********************@comcast.com...
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}

What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.


#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

struct Exception
{
Exception( char const* p ): m_what( p ) { }
std::string const& what( ) const { return m_what; }
private:
std::string const m_what;
};

void write( double d )
{
std::ofstream out( "file" );

if( ! out )
{
throw Exception( "can't write file" );
}

out << std::fixed << std::setprecision( 1000 ) << d;
}

double read( )
{
std::ifstream in( "file" );

if( ! in )
{
throw Exception( "can't read file" );
}

double d;

in >> d;

return d;
}

int main( )
try
{
float f( .1 );

write( f + 3 );

std::cout << std::fixed << std::setprecision( 1000 ) << read( )
<< "\n";
}
catch( Exception const& x )
{
std::cerr << x.what( ) << '\n';
return 1;
}

Jul 22 '05 #9
> Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point.
Bret thought that any programmer worth their salt would use the *appropriate*
numeric type and not create more work by needlessly keeping track of a radix.

Jeff Schwab wrote:
Drew wrote:
Hi:

I'm having trouble getting atof() to accurately convert "3.1"
Any ideas?

Thank you,

Drew

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{

float fNum;
char cNumBuffer[]="3.1";
fNum =(float)atof(cNumBuffer);
//Why does this store 3.099999905 in fNum

return 0;
}


What Ron said. Furthermore, 3.1 is provably unrepresentable as the
traditional sum of a finite sequence of integer powers of two, since .1
= 10^-1, and 10 has a prime factor other than two.

The GCC maintainers list this as their most often reported non-bug.

http://gcc.gnu.org/bugs.html#nonbugs

You can get a specified number of significant or reliable digits using
sprintf, or a more type-safe alternative. If you need to represent
rational numbers with absolute accuracy, get a library that supports
"common fractions." If you need to represent irrationals perfectly, you
might start by searching for "continued fractions;" these will help with
some of the non-transcendentals.

Personally, I avoid floating-point numbers whenever possible. Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point. If you must work with floating point
numbers in the same way you work with integers (e.g., you want to
compare them for equality), at least be careful to round them to a
realistic number of significant digits first.


--
Bret Pehrson
mailto:br**@infowest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl>>
Jul 22 '05 #10
Bret Pehrson wrote:
Von
Neumann also thought any programmers worth their salt should be able to
keep track of a radix point.

Bret thought that any programmer worth their salt would use the *appropriate*
numeric type and not create more work by needlessly keeping track of a radix.


And I would agree, provided one understands the limitations of the types
being considered and not just their benefits.

Jul 22 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Sreekanth | last post by:
Hello, Am trying to convert a string to float. Am using atof() for that purpose. But the return value for atof is same for the string "0.0" and for some invalid input "Invalid". Can any body...
4
by: ishekara | last post by:
Hi, As per the msdn knowledge base.. i find the following "In an application developed with Microsoft C or C/C++, the sscanf() function is a good alternative to the atof() function to convert...
15
by: XZ | last post by:
Hi everyone, this is really confusing to me: #include <stdio.h> main(int argc, char **argv) { printf("argv = %f\n",(double)atof(argv)); printf("argv = %d\n\n",atoi(argv)); } $ a.out a argv...
20
by: Trond Valen | last post by:
Hi! Stupid atof, it returns 0.0 when it tries to parse something like "fish". So I don't know whether the number was really 0 or a string that couldn't be parsed. Is there a better way to do...
21
by: oksuresh | last post by:
Hi talents, I have noticed that atof() function approximates the string I pass to it. when I use atof() , as atof(" 184.64") and it returns 184.63999999999 But I would like to have...
5
by: tjay | last post by:
Hi. I wrote some code using sprintf and atof to store a double as a string of fixed length and to convert it back to a double variable. The string is stored in a char buffer global variable. I'm...
14
by: sharmaharish | last post by:
I need a conversion function that converts values from string to a particular type. For this I have a template function that looks like this ... template<class T> T value(const string& s) {...
5
by: lcw1964 | last post by:
Greetings again, I will burden the group with yet another tenderfoot question, but since conscientious googling hasn't yield a lucid answer I thought I would risk the shortcut of asking here...
2
by: allexander | last post by:
Hello ! I need to convert a string like string number = "1235646.5678" to any floating point number x (double x or float x) I have used earlier the function atof()
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.