C++ 将数字格式化为特定的 QString 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7234824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:39:36  来源:igfitidea点击:

Format a Number to a specific QString format

c++qtstring-formattingqstring

提问by ImGreg

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.

我有一个关于将十进制数格式化为某种 QString 格式的问题。基本上,我的程序中有一个可以接受任何值的输入框。我希望它将此框中的值转换为格式“+05.30”(基于值)。该值将限制为 +/-99.99。

Some examples include:

一些例子包括:

.2 --> +00.02

.2 --> +00.02

-1.5 --> -01.50

-1.5 --> -01.50

9.9 --> +09.90

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).

我正在考虑使用这样的转换器,但它会有一些明显的问题(没有前导 0,没有前导 + 符号)。

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)

将 int 转换为带有零填充(前导零)的 QString

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

关于如何解决这个问题的任何想法?感谢您的帮助!谢谢!

回答by

I don't think you can do that with any QString method alone (either numberor arg). Of course you could add zeros and signs manually, but I would use the good old sprintf:

我认为您不能单独使用任何 QString 方法(numberarg)来做到这一点。当然,您可以手动添加零和符号,但我会使用旧的 sprintf:

double value = 1.5;
QString text;
text.sprintf("%+06.2f", value);

Edit:Simplified the code according to alexisdm's comment.

编辑:根据 alexisdm 的评论简化了代码。

回答by alexisdm

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:doubleToStringthat 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:

编辑:最糟糕的是,实际上有一个内部函数,QLocalePrivate:doubleToString它同时支持强制符号和两端的填充,但它仅与 中的这些选项一起使用QString::sprintf,而不是:

  • QTextStreamand 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.
  • QTextStream及其<<运算符,可以强制显示符号,但不能强制显示宽度或
  • QString::arg,这可以强制宽度但不能强制符号。

But for QTextStreamthat might be a bug.

但这QTextStream可能是一个错误。