Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Developer
Posts: 194
Registered: ‎11-24-2012
My Device: Dev Alpha B, Bold 9700
My Carrier: NA

format QString for float?

I've been looking through the docs here:

http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#arg

 

But can't seem to find a way to format a float/qreal value:

qreal floatValue = 1.1;
QString valueString = QString("%1").arg(floatValue); // should produce "1.10" with 2 decimal places following

 How can this be done?

Highlighted
Developer
Posts: 1,524
Registered: ‎12-18-2012
My Device: Z30, Z10 LE, DevAlpha C, PlayBook

Re: format QString for float?

If you need a quick solution for default C locale, here's a function I used for converting long doubles to QString. Decimal separator is a dot. Comment out "trim trailing zeros" section.

 

std::ostringstream o;
o.precision(2);
o << std::fixed;
o << value;
std::string s = o.str();

// Trim trailing zeros
size_t decimalPos = s.find_last_of('.');
if (decimalPos != std::string::npos)
{
  std::string::size_type trimAfter = s.find_last_not_of('0');
  if (trimAfter != std::string::npos)
    s.erase(trimAfter + 1);
  else
    s.clear(); // should never happen

  // Remove decimal dot at the end:
  decimalPos = s.find_last_of('.');
  if (decimalPos == s.length() - 1)
    s.erase(decimalPos, 1);
}

QString valueAsQString = QString::fromStdString(s);

 


Andrey Fidrya, @zmeyc on twitter
Developer
Posts: 194
Registered: ‎11-24-2012
My Device: Dev Alpha B, Bold 9700
My Carrier: NA

Re: format QString for float?

I think your way is more compatible with porting, but if anyone is using QString quite a bit, then this page has some good formatting info:

http://www.qtforum.org/article/29565/output-a-double-to-only-2-decimal-points.html

 

Thanks Zmey