21

I have a question about formatting a decimal number to a certain QString format. Basically, I have an input box in my program that can take any values. I want it to translate the value in this box to the format "+05.30" (based on the value). The value will be limited to +/-99.99.

Some examples include:

.2 --> +00.02

-1.5 --> -01.50

9.9 --> +09.90

I'm thinking of using a converter like this, but it will have some obvious issues (no leading 0, no leading + sign).

QString temp = QString::number(ui.m_txtPreX1->text().toDouble(), 'f', 2);

This question had some similarities, but doesn't tie together both front and back end padding.

Convert an int to a QString with zero padding (leading zeroes)

Any ideas of how to approach this problem? Your help is appreciated! Thanks!

Community
  • 1
  • 1
ImGreg
  • 2,946
  • 16
  • 43
  • 65

2 Answers2

32

I don't think you can do that with any QString method alone (either number or arg). Of course you could add zeros and signs manually, but I would use the good old sprintf:

double value = 1.5;
QString text;
text.sprintf("%+06.2f", value);

Edit: Simplified the code according to alexisdm's comment.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • 2
    Apparently, there is a [QString::sprintf](http://doc.qt.nokia.com/latest/qstring.html#sprintf) too. – alexisdm Aug 29 '11 at 21:03
  • Thanks, I made some changes to the answer. –  Aug 29 '11 at 21:21
  • While perhaps obvious, just to point it out, you can create a temp anonymous QString and use this function inline e.g. `QString().sprintf(...)`. That can be handy when swapping this for the static, more straight forward, `QString::number(...) ` function. – BuvinJ Apr 16 '19 at 12:29
  • 1
    `QString().sprintf(...)` is sadly deprecated. https://doc.qt.io/qt-5/qstring-obsolete.html#sprintf – Scrumplex Jan 20 '22 at 12:14
14

You just have to add the sign manually:

QString("%1%2").arg(x < 0 ? '-' : '+').arg(qFabs(x),5,'f',2,'0'); 

Edit: The worst thing is that there is actually an internal function, QLocalePrivate:doubleToString that supports the forced sign and the padding at both end as the same time but it is only used with these options in QString::sprintf, and not:

  • QTextStream and its << operator, which can force the sign to show, but not the width or
  • QString::arg, which can force the width but not the sign.

But for QTextStream that might be a bug.

alexisdm
  • 29,448
  • 6
  • 64
  • 99