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

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:



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?

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 << 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);
    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
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:



Thanks Zmey