Qt編程常見問題1:關於int、double、string、QString格式相互轉換的方法

轉自https://blog.csdn.net/qq_35223389/article/details/83112753?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase

1,int與double
//int轉double
int a = 1234;
double b;
b = a;//直接賦值就可以

//double轉int
double c = 123.456;
int d;
d = c;//d的結果爲123,即只取整數部份
d = c*1000;//乘1000將小數消掉即可,注意int位數要求,避免溢出

2,int與string
//int轉string
int a = 123456;
string b;
b = std::tostring(a);

//string轉int
string c = "123456";
int d;
d = atoi(c.c_str());//string轉float 用 atof()

3,int與QString
//int轉QString
int a = 123456;
QString b;
b = QString::number(a,10,5);//QString::number(a,基底,精度)
//方法2,利用arg()
int a = 123456;
QString b = QString("%1").arg(a);

//QString轉int
QString c = "123456";
int d;
d = c.toInt();

4,double與QString
//double轉QString
double a = 123.456;
QString b;
b =  QString::number(a,10,5);//同int

//QString轉double
QString c = "123.456";
double d;
d = c.toDouble();//類似int

5,string與QString
//string轉QString
string a = "123.456";
QString b;
b = QString::fromStdString(a);

//QString轉string
QString c = "123,456";
string d;
d = c.toStdString();
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章