# converting double to string

• 02-04-2002
vusak
converting double to string
i wrote something to convert a string to a double, no probs there, but i cant reverse the process. i definitely need to be able to convert a double to a string, there is no way around it. any ideas on how to do it?

i thought it might involve iterating through % operations, working from 10^0 through to 10^(number of digits) but im a little unsure of how this will work, plus there is the problem of a decimal point. i wont have to worry about doubles with exponents, so i guess that simplifies it a little :)

any ideas?
• 02-04-2002
sprintf()
• 02-04-2002
Betazep
write it to a file as a double. Read it as a char array. Put null character at the end. Lengthy... but effective. ;)

You could write one function to do this, and just call the function.

*char convert (Type number);
• 02-05-2002
vusak
solution :)
i got this tip from another board, but i thought id share it,

#include <sstream>
#include <string>

...

double d = 10.427;
double d2;
std::string s;
std::stringstream ss, ss2;

ss << d; //put d into the stringstream
ss >> s; //put this value into s

//now s is a string holding "10.427"
//Convert the other way. Use ss2 and d2.

ss2 << s;
ss2 >> d2;

//d2 now holds 10.427, converted from the string s

i had to play around with char* [] and stuff because i had a different implementation of string, but needless to say, it worked a charm, id also worked out another way, but this is much cleaner :)

btw thanks for your help :)
• 02-05-2002
Magos