将数字格式化为特定的 QString 格式 [英] Format a Number to a specific QString format

查看:41
本文介绍了将数字格式化为特定的 QString 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于将十进制数格式化为某种 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.

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆