tags:

views:

401

answers:

3

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 doubletype.

Thanks

+5  A: 

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();
}
wheaties
Assumes `using namespace std;`, right?
Mike D.
@Mike: better to assume `using std::string; using std::stringstream;`
Bill
Actually, I use `std::string` and `std::stringstream`. I'm not a big fan of `using`; like `#include`, it puts important information out of view of most of the source (i.e. `#include` and `using` statements are usually at the start of the source file, so you have to look back from wherever you are to gain context). I just brought this up because there are a *lot* of programmers that put `using namespace std;` in *all* their code and assume everyone else does as well.
Mike D.
A: 

Boost has lexical_cast for this purpose. It pretty much wraps the solution wheaties gave into a class template.

Fred Larson
+2  A: 

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());
}
Bill
Also possible is `return QString(ss.str().c_str());`
Adam W
@Adam: `QString::fromStdString()` can use the `std::string`'s size() to avoid counting the length of the string. If you pass a bare `const char*` to `QString()` then it has to recalculate what is already known.
Bill
@Bill: right, good to know. I usually get to avoid all of this with `QString("%1").arg(n)` but it doesn't handle long double :)
Adam W