If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:
#include <boost/lexical_cast.hpp>
#include <string>
// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);
In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.
For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)
(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)
The problem with lexical_cast is the inability to define precision. Normally if you are converting a double to a string, it is because you want to print it out. If the precision is too much or too little, it would affect your output.
The Standard C++11 way (if you don't care about the output format):
#include <string>
auto str = std::to_string(42.5);
to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) "Simple Numeric Access". There are also the stod function to perform the reverse operation.
If you do want to have a different output format than "%f", use the snprintf or ostringstream methods as illustrated in other answers.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string pi = "pi is " + to_string(3.1415926);
cout<< "pi = "<< pi << endl;
return 0;
}
Note that a string is just a representation of the double and converting it back to double may not result in the same value.
Also note that the default string conversion may trim the conversion to a certain precision.
In the standard C++ way, you can control the precision as follows:
#include <sstream>
#include <math.h>
#include <iostream>
#include <iomanip>
int main()
{
std::ostringstream sout;
sout << M_PI << '\n';
sout << std::setprecision(99) << M_PI << '\n';
sout << std::setprecision(3) << M_PI << '\n';
sout << std::fixed; //now the setprecision() value will look at the decimal part only.
sout << std::setprecision(3) << M_PI << '\n';
std::cout << sout.str();
}
std::to_chars_result to_chars( char* first, char* last, float value,
std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, double value,
std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, long double value,
std::chars_format fmt, int precision );
Which provide fast low level way to convert floating points into string with some level of format control. This should be fast since no allocation is done, only custom implementation for specific scenario should be faster.
C++20 has introduced high level easy to use format string (equivalent of fmt library):