Search code examples
c++stringdouble

How do I convert a double into a string in C++?


I need to store a double as a string. I know I can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).


Solution

  • The boost (tm) way:

    std::string str = boost::lexical_cast<std::string>(dbl);
    

    The Standard C++ way:

    std::ostringstream strs;
    strs << dbl;
    std::string str = strs.str();
    

    Note: Don't forget #include <sstream>