Format the number in a specific QString format

I have a question about formatting a decimal number in a specific QString format. Basically, I have an input window in my program that can take any values. I want it to convert the value in this field to the "+05.30" format (depending 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 think about using such a converter, but it will have some obvious problems (no pointers 0, no + sign).

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

This question had some similarities, but does not connect the front and rear gasket.

Convert int to QString with zero padding (leading zeros)

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

+8
c ++ qt string-formatting qstring
source share
2 answers

I do not think you can do this with any QString method ( 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 code as per alexisdm comment.

+18
source share

You just need to add the character manually:

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

Change The worst part is that there is actually an internal function QLocalePrivate:doubleToString , which supports the forced sign and indentation at both ends at the same time, but is used only with these parameters in QString::sprintf , and not:

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

But for QTextStream this may be a mistake.

+8
source share

All Articles