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.
views:
14355answers:
12// The C way:
char buffer[32];
snprintf(buffer, 32, "%g", myDoubleVar);
// The C++ way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();
// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);
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:
template <typename T>
std::string to_string(T const& value) {
stringstream sstr;
sstr << value;
return sstr.str();
}
Usage:
string s = to_string(42.5);
Heh, I just wrote this (unrelated to this question):
string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();
/* rest of the code */
sprintf
is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream
:
#include <sstream>
#include <string>
// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();
You can also use Boost.LexicalCast:
#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 stringstream
s internally.
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();
Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.
A question to answer your question: why are you storing the double value in a string to store it in a map? Are you going to use the string-ified double as the key? If not, why not leave the double as is?
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.