C++: what is the optimal way to convert a double to a string?

Boost::lexical_cast<>


I'm sure someone will say boost::lexical_cast, so go for that if you're using boost, but it's basically the same as this anyway:

 #include <sstream>
 #include <string>

 std::string doubleToString(double d)
 {
    std::ostringstream ss;
    ss << d;
    return ss.str();
 }

Note that you could easily make this into a template that works on anything that can be stream-inserted (not just doubles).


http://www.cplusplus.com/reference/iostream/stringstream/

double d=123.456;
stringstream s;
s << d; // insert d into s

Tags:

C++

C