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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2618414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:06:48  来源:igfitidea点击:

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

c++qtqstring

提问by elcuco

I want to "stringify" a number and add zero-padding, like how printf("%05d")would add leading zeros if the number is less than 5 digits.

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

回答by chalup

Use this:

用这个:

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

5 here corresponds to 5 in printf("%05d"). 10 is the radix, you can put 16 to print the number in hex.

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

回答by Дмитрий Гранин

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

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

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

result is now 00099

结果现在是 00099

回答by user1767754

The Short Example:

简短示例:

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

回答by Isaac

Try:

尝试:

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


EDIT: According to the docs at http://qt-project.org/doc/qt-4.8/qstring.html#sprintf:

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

Warning: We do not recommend using QString::sprintf() in new Qt code. Instead, consider using QTextStream or arg(), both of which support Unicode strings seamlessly and are type-safe. Here's an example that uses QTextStream:

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

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

Read the other docs for features missing from this method.

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

回答by Ramao Balta

I use a technique since VB 5

我使用自 VB 5 以来的技术

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

回答by elcuco

I was trying this (which does work, but cumbersome).

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

QString s;
s.setNum(n,base);
s = s.toUpper();
presision -= s.length();
while(presision>0){
    s.prepend('0');
    presision--;
}