1.數值轉QString
QT提供了一系列將數值轉換為QString的靜態函數
1 QString number(long n, int base = 10) 2 QString number(ulong n, int base = 10) 3 QString number(int n, int base = 10) 4 QString number(uint n, int base = 10) 5 QString number(qlonglong n, int base = 10) 6 QString number(qulonglong n, int base = 10) 7 QString number(double n, char format = 'g', int precision = 6)
整形的轉換格式都是一樣的,第一個參數是十進制要轉換的整數,第二個參數指定以什么進制來轉換,默認是十進制,比如:
1 QString strNumDec = QString::number(55, 10); 2 QString strNumHex = QString::number(55, 16); 3 QString strNumBit = QString::number(55, 2); 4 5 qDebug() << strNumDec;//"55" 6 qDebug() << strNumHex;//"37" 7 qDebug() << strNumBit;//"110111"
第二個參數base必須在[2,36]之間,當base為10以外的值時,第一個參數n將被視為無符號整數。
2.QString轉數值
1 double toDouble(bool * ok = 0) const 2 float toFloat(bool * ok = 0) const 3 int toInt(bool * ok = 0, int base = 10) const 4 long toLong(bool * ok = 0, int base = 10) const 5 qlonglong toLongLong(bool * ok = 0, int base = 10) const 6 short toShort(bool * ok = 0, int base = 10) const
QString也提供了一系列轉換成數值的函數,參數ok指示轉換是否出錯,參數base指示當前QString是什么進制,如:
1 QString str = "55"; 2 bool ok; 3 4 int numBit = str.toInt(&ok, 2); 5 qDebug() << ok << ":" << numBit;//false : 0 6 7 int numOct = str.toInt(&ok, 8); 8 qDebug() << ok << ":" << numOct;//true : 45 9 10 int numDec = str.toInt(&ok, 10); 11 qDebug() << ok << ":" << numDec;//true : 55 12 13 int numHex = str.toInt(&ok, 16); 14 qDebug() << ok << ":" << numHex;//true : 85
此外,QLocale也提供了一系列QString與數值之間轉換的函數。