float/double to string

Jun 12, 2009 at 5:19pm
How do I convert float and double variables into null-terminated strings (without string stream, if possible)
Jun 12, 2009 at 5:28pm
Try with boost::lexical_cast
What's wrong with stringstreams anyway?
Jun 12, 2009 at 5:35pm
Doesn't boost::lexical_cast use stringstreams?
Jun 12, 2009 at 6:45pm
It does.
Jun 13, 2009 at 6:39am
Okay, I'll probably use stringstream, but I would still like to know how exactly the conversion is done. Can you please explain to me how float and double are converted to strings?
Jun 13, 2009 at 6:53am
closed account (S6k9GNh0)
I have no clue. My only guess is that it hard codes values for individual numbers 0-9 then breaks each character in a string down and then converts it multiplying by 10^x where x equals the position in the string.

Jun 13, 2009 at 8:43am
I'd like someone who does have a clue to answer. Anyway, multiplying by 10^x is a waste of processing time. You get the digits using number % 10 and floor(number/10) gives you the number for the next step. The question is how the exponent is saved. I'm not asking about int to string because I know how this conversion is done. float to string and double to string are different. A little more complicated (reading the exponent and determining where the decimal dot is).
By the way, the %10 method reads the digits right-to-left. So you need to allocate a char array with enough space for the whole number.
Last edited on Jun 13, 2009 at 8:47am
Jun 13, 2009 at 12:00pm
It depends on the floating-point number format. For IEEE, converting fp to string is very much the same as converting int to string.

In any case, the C/C++ library is as efficient as it gets when doing the conversions... you don't have to worry about it.

Unless you want to write your own, then you'll have to spend some more time thinking about it. There was a thread on this very topic not too long ago.
http://www.cplusplus.com/forum/general/10898/

Hope this helps.
Topic archived. No new replies allowed.