qt控制字符串中控制小数精度

本文介绍了在Qt中使用QString进行数字格式化的三种方式,包括arg()函数、setNum()方法和number()静态函数。示例展示了如何使用e、E、f和g格式控制精度,以及设置小数点后的位数和最大有效位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Format Meaning
e   format as [-]9.9e[+|-]999
E   format as [-]9.9E[+|-]999
f   format as [-]9.9
g   use e or f format, whichever is the most concise
G   use E or f format, whichever is the most concise

A precision is also specified with the argument format. For the 'e', 'E', and 'f' formats, 
the precision represents the number of digits after the decimal point. 
For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).

参数格式还指定了精度。对于“e”、“e”和“f”格式,精度表示小数点后的位数。对于“g”和“g”格式,精度表示最大有效位数(省略尾随零)。

方式一:
QString QString::arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = QLatin1Char( ' ' )) const

例1:
double a = 3.14000000;
QString str1 = QString("%1").arg(a,10,'f',6);  //3.140000
QString str2 = QString("%1").arg(a,10,'g',6);  //3.14


方式二:
QString &QString::setNum(float n, char format = 'g', int precision = 6)
QString &QString::setNum(doublen, char format = 'g', int precision = 6)

例2:
double a = 3.14000000;
QString str2;
str2.setNum(a,'f',6);  //3.140000

方式三:
[static] QString QString::number(double n, char format = 'g', int precision = 6)

例3:
double a = 3.14000000;
QString str = QString::number(a,'f',6);  //3.140000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值