将数字格式化为特定的 QString 格式 [英] Format a Number to a specific QString format
问题描述
我有一个关于将十进制数格式化为某种 QString 格式的问题.基本上,我的程序中有一个可以接受任何值的输入框.我希望它将此框中的值转换为格式+05.30"(基于值).该值将限制为 +/-99.99.
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.
一些例子包括:
.2 --> +00.02
.2 --> +00.02
-1.5 --> -01.50
-1.5 --> -01.50
9.9 --> +09.90
9.9 --> +09.90
我正在考虑使用这样的转换器,但它会有一些明显的问题(没有前导 0,没有前导 + 符号).
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.
关于如何解决这个问题的任何想法?感谢您的帮助!谢谢!
Any ideas of how to approach this problem? Your help is appreciated! Thanks!
推荐答案
我认为您无法单独使用任何 QString 方法(编号 或 arg).当然,您可以手动添加零和符号,但我会使用旧的 sprintf:
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);
根据 alexisdm 的注释简化了代码.
Simplified the code according to alexisdm's comment.
这篇关于将数字格式化为特定的 QString 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!