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

十年热恋 提交于 2019-11-28 21:47:32

问题


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.


回答1:


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.




回答2:


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




回答3:


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



回答4:


Try:

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

EDIT: According to the docs at 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:

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

Read the other docs for features missing from this method.




回答5:


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--;
}



回答6:


I use a technique since VB 5

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



回答7:


function zeroPad(num, places) {
        num = num.toString().toUpperCase();
        return num.length < places ? zeroPad("0" + num, places) : num;
    }

I use this recursive function to pad zero!



来源:https://stackoverflow.com/questions/2618414/convert-an-int-to-a-qstring-with-zero-padding-leading-zeroes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!