qtformattingqtextstream

QTextStream fixed point formatting issue


I'm having an issue with the QTextStream formatting. I'm using the code below to print a percentage from a quint8 and it seems to be giving me a space in between the number and the decimal point. For example, I'll get "50 %" instead of "50%" and "100 %" instead of "100%".

What's my problem?

QString retVal;
QTextStream retStream(&retVal);
retStream.setRealNumberNotation(QTextStream::FixedNotation);
retStream.setRealNumberPrecision(0);
retStream << qSetFieldWidth(2)
          << (100*((float)myQuint8)/255.0) << "%";
return retVal;

Solution

  • From the QTextStream::setFieldWidth documentation

    Note: The field width applies to every element appended to this stream after this function has been called (e.g., it also pads endl). This behavior is different from similar classes in the STL, where the field width only applies to the next element.

    So you need to reset the field width to zero before you output the '%' character.