将数字格式化为特定的 QString 格式
我有一个关于将十进制数格式化为某种 QString 格式的问题。基本上,我的程序中有一个可以接受任何值的输入框。我希望它将这个框中的值转换为格式“+05.30”(基于该值)。该值将限制为 +/-99.99。
一些例子包括:
.2 --> +00.02
-1.5 --> -01.50
9.9 --> +09.90
我正在考虑使用这样的转换器,但它会有一些明显的问题(没有前导 0,没有前导 + 符号)。
QString temp = QString::number(ui.m_txtPreX1->text().toDouble(), 'f', 2);
这个问题有一些相似之处,但没有将前端和后端填充联系在一起。
关于如何解决此问题的任何想法?感谢您的帮助!谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您不能单独使用任何 QString 方法来做到这一点( number< /a> 或 arg)。当然,您可以手动添加零和符号,但我会使用旧的 sprintf:
编辑: 根据 alexisdm 的评论简化了代码。
编辑:此方法已被删除。从 Qt 5.5 开始,替换为 QString::asprintf。
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:
Edit: Simplified the code according to alexisdm's comment.
Edit: This method has been removed. Since Qt 5.5, the replacement is QString::asprintf.
您只需手动添加符号即可:
编辑:最糟糕的是实际上有一个内部函数
QLocalePrivate:doubleToString
支持强制符号和填充同时结束,但它仅与QString::sprintf
中的这些选项一起使用,而不是:QTextStream
及其<<
运算符,可以强制符号显示,但不显示宽度或但对于 QTextStream 来说这可能是一个错误。
You just have to add the sign manually:
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 inQString::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.