繁体   English   中英

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

[英]Convert an int to a QString with zero padding (leading zeroes)

我想“字符串化”一个数字并添加零填充,就像printf("%05d")在数字小于 5 位时如何添加前导零一样。

用这个:

QString number = QStringLiteral("%1").arg(yourNumber, 5, 10, QLatin1Char('0'));

这里的 5 对应于printf("%05d") 10 是基数,你可以把 16 打印成十六进制的数字。

QString QString::rightJustified ( int width, QChar fill = QLatin1Char( ' ' ), bool truncate = false ) const

int myNumber = 99;
QString result;
result = QString::number(myNumber).rightJustified(5, '0');

结果现在是 00099

简短示例:

int myNumber = 9;

//Arg1: the number
//Arg2: how many 0 you want?
//Arg3: The base (10 - decimal, 16 hexadecimal - if you don't understand, choose 10)
//      It seems like only decimal can support negative numbers.
QString number = QString("%1").arg(myNumber, 2, 10, QChar('0')); 

Output will be: 09

尝试:

QString s = s.sprintf("%08X",yournumber);

编辑:根据http://qt-project.org/doc/qt-4.8/qstring.html#sprintf上的文档:

警告:我们不建议在新的 Qt 代码中使用 QString::sprintf()。 相反,请考虑使用 QTextStream 或 arg(),它们都无缝支持 Unicode 字符串并且是类型安全的。 下面是一个使用 QTextStream 的例子:

QString result;
QTextStream(&result) << "pi = " << 3.14;
// result == "pi = 3.14"

阅读其他文档以了解此方法中缺少的功能。

我使用自 VB 5 以来的技术

QString theStr=QString("0000%1").arg(theNumber).right(4);

我正在尝试这个(确实有效,但很麻烦)。

QString s;
s.setNum(n,base);
s = s.toUpper();
presision -= s.length();
while(presision>0){
    s.prepend('0');
    presision--;
}
function zeroPad(num, places) {
        num = num.toString().toUpperCase();
        return num.length < places ? zeroPad("0" + num, places) : num;
    }

我使用这个递归函数来填充零!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM