adam_0 adam_0 - 1 year ago 168
C++ Question

Convert float to std::string in C++

I have a float value that needs to be put into a

. How do I convert from float to string?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download