This topic is now archived and is closed to further replies.


double to char conversion

Recommended Posts

Wouldn''t it be easier if you tried it out first? It only takes 3 or 4 lines of code! Besides, there is nothing like seeing the result for yourself and interpreting the result.

"There is no dark side of the moon." - Pink Floyd

Share this post

Link to post
Share on other sites

Well I have seen from experience that trying to choose which of the three codes, gcvt() , ecvt() , and fcvt() can be difficult.

I recommend gcvt() in this case. I'm not sure you are handling scientific notations, "ecvt() " or "fcvt() ", so we will stick with "gcvt() ".

Now I wrote a sample code that converts a double floating point to a string, and back, using the standard library functions. I also used atof() to convert a string back to a floating point. Of course you might think that a double is not the same as a float. Well in all cases you see the names are different, only thing that is different with the double is it supports 32-bit, while float 24 or 16, and integer 8.

#include <stdio.h>
#include <stdlib.h>

int main() {
char buffer[50];
int precision = 5;
double value = 245.92;

// Convert to string

gcvt(value, precision, buffer);
printf("%s\n", buffer);

// Convert back to double

value = atof(buffer);
printf("%f\n", value);

return 0;
Example 1.1: Converting a double to string and vice-versa using gcvt() and atof()

Alright, well the example is simple and well explained. I'll just explain up on gcvt() .

· The first parameter handles the value , others say the floating point (double in this case). It retrieves whatever is stored in this data type variable.
· The second parameter, precision , tells the function how many numbers it is going to convert. For instance, if precision were 3 in this example all that would convert is "245", else if precision were 4 the outcome would be "245.9", and so on and so forth.
· The third parameter, of course, needs a buffer to write too. So you just seed one to it and it automatically writes the info in your string.

I hope this has helped,

[edited by - BlueDev on March 23, 2004 11:41:25 AM]

Share this post

Link to post
Share on other sites
or better yet if you're using C++

#include <string>
#include <sstream>

int main()
double x = 23.3;
std::stringstream str;

str << x << std::ends;

std::string result = str.str();


"That's not a bug, it's a feature!"

[edited by - ChaosEngine on March 23, 2004 8:14:36 PM]

Share this post

Link to post
Share on other sites
one more question what''s the biggest number a char can hold? Is it 0 - 255 since the biggest number 1 byte can hold is 11111111 which is 255. also how does a char or any other type store if the number is negative?

Share this post

Link to post
Share on other sites