7

I would like to format an integer in a QString. I would like to always have 6 numbers. For example "1" should be "000001" and "12" should be "000012".

I try to do like with printf(%06d, number). So I wrote this

QString test; test = QString("%06d").arg(QString::number(i)); qDebug()<<test;

i is implemented in a loop for. But it does not work since I have:

"0d" "1d" "2d" "3d"...

Does anyone know how to do this please?

Jeanstackamort
  • 309
  • 2
  • 4
  • 16
  • If you read the documentation of QString::arg(), you will understand the results you're getting – RobbieE Feb 25 '14 at 15:01

3 Answers3

7

String's argument support doesn't work like printf. It's all documented. What you want is:

QString test = QString("%1").arg(i, 6, 10, QLatin1Char('0'));
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
0

You could try the following:

int a = 12;
QString test = QString("%1").arg(a, 6, 'g', -1, '0');
qDebug() << test; // outputs "000012"
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • 1
    This unnecessarily uses the `arg` overload for doubles. It will fail spectacularly if the platform `int` is a 64 bit type, or if the declaration ever gets changed to `qint64`. By failing spectacularly I mean that there will be digits in the result that are simply wrong. It will fail just the same if the platform's `double` type is equal to `float` and happens to be 32 bits wide (as allowed by the standard). So this is pretty much unportable and not recommended at all. – Kuba hasn't forgotten Monica Feb 25 '14 at 15:08
0

Have a look in the documentation for QTextStream. There are a number of settings for formatting as well as a number of handy manipulators. This is analogous to the text manipulators from STL iostream

RobbieE
  • 4,280
  • 3
  • 22
  • 36