QT 关于QString的格式化(补零/进制转换)

QString的格式化,我们主要用到的是arg()函数,该函数有很多重载:

QString 
arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(long a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(ulong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(uint a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(short a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(ushort a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString 
arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = QLatin1Char(' ')) const

参数解析:

  • fieldWidth 代表限制的字符串宽度
  • base 代表进制
  • fillChar 代表填充的字符

1、限制字符串宽度,不够则在前面补零

//限制字符串宽度,不够则在前面补零
QString strNumber = QString::number(23);
//十进制数23,字符串宽度:4
QString strConv = QString("%1").arg(strNumber.toInt(), 4, 10, QLatin1Char('0'));
qDebug() << "strConv=" << strConv;//0023

//十进制的23 转为十六进制数,字符串宽度:4
strConv = QString("%1").arg(strNumber.toInt(), 4, 16, QLatin1Char('0'));
qDebug() << "strConv=" << strConv;//0017

//十进制32 转为十六进制,,字符串宽度:0
strConv = QString("%1").arg(32, 0, 16);
qDebug() << "strConv=" << strConv;//20

字符串补零的手动版本:

QString fillWithZero(const QString& src, int length)
{
	QString pattern;
	for (int i = 0; i < length; i++)
		pattern.append("0");
	return (pattern + src).right(length);
}

2、保留小数点后几位数

//整数转QString
QString strInt = QString::number(123);
qDebug() << "strInt=" << strInt;

//小数转QString,保留两位小数
QString strDouble = QString::number(123.456789, 'f', 2);
qDebug() << "strDouble=" << strDouble;//123.46

3、时间格式hh:mm:ss

//时间显示格式(12:3:7 > 12:03:07)
QDateTime dt = QDateTime::currentDateTime();
QTime tm = dt.time();
int h = tm.hour();
int m = tm.minute();
int s = tm.second();
QString strTime = QString("%1:%2:%3")
	.arg(h, 2, 10, QLatin1Char('0'))
	.arg(m, 2, 10, QLatin1Char('0'))
	.arg(s, 2, 10, QLatin1Char('0'));
qDebug() << "time=" << strTime;

//asprintf
strTime = QString::asprintf("%02d:%02d:%02d", h, m, s);
qDebug() << "time=" << strTime;

(443条消息) QT 关于QString的格式化(补零/进制转换)_hellokandy的博客-CSDN博客_qstring格式化字符串

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值