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.