# converting double to string

This is a discussion on converting double to string within the C++ Programming forums, part of the General Programming Boards category; i wrote something to convert a string to a double, no probs there, but i cant reverse the process. i ...

1. ## 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?

2. sprintf()

3. 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);

4. ## 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

5. ## reply

I'm not sure, but isn't there a function like dtoa()??? I know there is a itoa() that converts intergers to arrays (strings) (i to a = itoa).

6. nope! itoa or ftoa are not standard functions... some compiler may provide them...

the C++ way to do this conversation is strtream or stringstream

the C way is sprintf()

7. all double values have exp. you just dont see them.
yeah, sprintf

Popular pages Recent additions