Latest LQ Deal: Linux Power User Bundle
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 08-03-2005, 09:59 AM   #1
Registered: Oct 2004
Distribution: Debian, Ubuntu
Posts: 38

Rep: Reputation: 15
[C++] char * to float

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?
Old 08-03-2005, 10:42 AM   #2
Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 32
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.

#include <iostream>
#include <iomanip>

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

    std::cout << std::setprecision(14) << f << std::endl;
    return 0;
Old 08-03-2005, 11:28 AM   #3
jim mcnamara
Registered: May 2002
Posts: 964

Rep: Reputation: 36
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:


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
count digits of a float || convert float to string nadroj Programming 6 07-11-2005 05:52 PM
C pointers confusion - char ** = char [][] ?? saravkrish Programming 12 12-02-2004 11:06 AM
C Problem---convert char to char* totti10 Programming 11 11-06-2004 12:32 PM
invalid conversion from `char' to `const char* bru Programming 6 05-09-2004 04:07 PM
convert from char* to unsigned char* D J Linux - Software 2 02-20-2004 05:09 AM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:55 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration