Format a Number to a specific QString format
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开发者_JS百科 (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!
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.
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 orQString::arg
, which can force the width but not the sign.
But for QTextStream
that might be a bug.
精彩评论