views:

235

answers:

4

This is a seemingly simple problem, but I'm having difficulty coming up with an answer. I have a float value that needs to be put into a std::string, like so:

float val = 2.5;
std::string my_val = val; // error here

Obviously they're of different types. How do I convert from float to string?

All help is appreciated.

+6  A: 

Unless you're worried about performance, use string streams:

std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());

If you're okay with Boost, lexical_cast<> is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(myFloat);

Efficient alternatives are e.g. FastFormat or simply the C-style functions.

Georg Fritzsche
This will be an adequate solution considering that these functions will be called rarely (resizing the window), but is there a more efficient method?
adam_0
And if you're not okay with Boost, write your own lexical cast function; it's all of about five lines of code and makes for a most useful library function (see http://www.gotw.ca/publications/mill19.htm for the basic implementation).
James McNellis
+3  A: 

Check the must-read C++ FAQ by Marshall Cline and the question:

mloskot
+2  A: 

If you're worried about performance, check out the Boost::lexical_cast library.

David Gladfelter
I think you mean "if you're *not* worried about performance". `boost::lexical_cast` is about the heaviest solution you could pick!
Tom
+3  A: 

You can define a template which will work not only just with doubles, but with other types as well.

template <typename T> string tostr(const T& t) { ostringstream os; os<<t; return os.str(); } 

Then you can use it for other types.

double x = 14.4;
int y = 21;

string sx = tostr(x);
string sy = tostr(y);
dcp