Format a Number to a specific QString format

谁都会走 提交于 2021-02-07 11:25:13

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7234824/format-a-number-to-a-specific-qstring-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!