LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [C++] char * to float (https://www.linuxquestions.org/questions/programming-9/%5Bc-%5D-char-%2A-to-float-349570/)

Ossar 08-03-2005 08:59 AM

[C++] char * to float
 
Code:

char * c = "-6.02059991328";
float f = atof(c);

When examining "f" I get: -6.0205998420715

Tha atof function returns a double value and it is probably this that makes the float loose data? How do I convert a char * to a float?

deiussum 08-03-2005 09:42 AM

Try using a double instead of a float. floats are notorious for losing precision due to the way they are stored. doubles can lose precision as well, but are much more precise than floats. If the double isn't as precise as you need you may need to use some sort of fixed point math library.

I think that you'll find that if you try and set f to your value directly, the same thing will happen.

Code:

#include <iostream>
#include <iomanip>

int main(int argc, char** argv)
{
    float f = -6.02059991328;

    std::cout << std::setprecision(14) << f << std::endl;
    return 0;
}

Result:
-6.0205998420715

jim mcnamara 08-03-2005 10:28 AM

look in limits.h for FLT_DIG - which is usually 6.
This means floats are guaranteed to be accurate in six places only.

DBL_DIG is usually 15.

If you think that numbers like these should be accurate to umpteen places read what IEEE has to say about floating point numbers:

http://cch.loria.fr/documentation/IE...M/goldberg.pdf


All times are GMT -5. The time now is 08:25 PM.