0

How do I format a number the following way?

input:

123

output:

1.2-3

In C#, there's a ToString() overload for integer types that does the job:

123.ToString(@"0\.0-0"); //output 1.2-3

Is there something like this in Qt? I did read QString documentation but couldn't manage to do that.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Jack
  • 16,276
  • 55
  • 159
  • 284

2 Answers2

2

There is no built-in function for formatting an integer to string, but you can perform your custom formatting by your own custom function to do so.

Gaurav
  • 111
  • 3
2

For example, you could do:

int number = 123;
QString s = QString("%1.%2-%3").arg(
    QString::number((number / 100) % 10),
    QString::number((number / 10) % 10),
    QString::number(number % 10));

or:

QString s = QString::number(123);
s.insert(1, QChar('.'));
s.insert(3, QChar('-'));
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • The second approach seems better in my case since the number is a bit larger than the one in my example e: but this result in a lot of reallocations.. – Jack Nov 28 '15 at 17:40
  • I thought you only needed to do it for three-digit numbers. You might also want to check, whether the number is negative if that's a possibility. – LogicStuff Nov 28 '15 at 18:04