Jump to content
  • Advertisement
Sign in to follow this  
zoner7

Converting floats to strings

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 use

ss.str();

Share this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites
To answer your original question, lexical_cast() is header-only, so all you need to do is download the Boost libraries, add the path to the header search paths for the project, and #include <boost/lexical_cast.hpp>.

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!