# Converting floats to strings

This topic is 2772 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

As I understand, there are two ways to do this:

Either I can use stringstream instead of string, or I can use
boost::lexical_cast<std::string>(my_float);

I am leaning towards the later because my quite extensive entire program is already using strings, and it would be a disaster trying to change everything. Additionally, SFML (which I am using) accepts strings, and I suspect I would run into trouble if I begin using stringstream.

In essence, I am curious what exactly I need to download. There appears to be one big boost zip file on their website, but I imagine that I only need a specific file.

Is it necessary for me to compile anything myself? The website mentions that the library is primarily composed of .hpp files, barring a few specific files. Is the function I am looking for contained in a file that I will need to compile myself?

Thank you.

##### Share on other sites
string stream isn't that hard to use for conversion, I don't know if it's the most optimal though.

std::stringstream ss;float myFloat = 5.0;ss << myFloat;// then to get the string in stringstream usess.str();

##### Share on other sites
how about a function with a float as input and string as output?

something along the lines of:

std::string floatToString(float f)
{
std::ostringstream s;
s << f;
return s.str();
}

but maybe i misunderstood your intentions

edit: 2 late

or using good old sprintf

(untested)

std::string floatToString(float f)
{
char buffer[256];

sprintf(buffer, "%f", f);

return std::string(buffer);
}

##### Share on other sites
I ended up using the first of your two suggestions, Scope. It worked like a charm. Thanks a ton.

##### Share on other sites

There's lots of other useful stuff in the Boost libraries as well, and once you've done the above steps, you'll have access to most of it. (Some of the libraries require compilation, so if you want to use any of those, you'll have to either compile the libraries, or find a binary distribution.)