Reputation: 27047
I'm developping in C++, using the Qt framework.
I need to convert a long double
value into a string (ideally a QString
, but could be something else).
So far, I always used QString::number() for numerical->string conversion, but there is no overloading for the long double
type.
Thanks
Upvotes: 2
Views: 9330
Reputation: 51
The answer marked is not complete, it will save it with only 6 decimal digits. It should be like this:
#include <sstream>
#include <iomanip>
#include <limits>
QString longDoubleToString(long double value)
{
std::stringstream stream;
stream << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << value;
return QString::fromStdString(stream.str());
}
Upvotes: 0
Reputation: 35990
Simple:
string convert(long double myLongDouble) {
stringstream blah;
blah << myLongDouble;
return blah.str();
}
With Templates:
template<class T> string convert(T _input) {
stringstream blah;
blah << _input;
return blah.str();
}
Upvotes: 5
Reputation: 14695
QString has a static function to construct a QString from a std::string, so wheaties' answer could be rewritten as:
#include <sstream>
#include <QString>
...
QString qStringFromLongDouble(const long double myLongDouble)
{
std::stringstream ss;
ss << myLongDouble;
return QString::fromStdString(ss.str());
}
Upvotes: 5
Reputation: 62123
Boost has lexical_cast
for this purpose. It pretty much wraps the solution wheaties gave into a class template.
Upvotes: 0