QString与int,double之间的转换

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与数值之间转换的函数。

 

posted @ 2016-03-27 00:57  aloog  阅读(6633)  评论(0编辑  收藏  举报