QT, QString, QVaint, toDouble时造成精度丢失
QString, QVaint, toDouble时造成精度丢失
·
如:
str = "107.2804"
double d = str.toDouble() => 107.28
或
QByteArray b = str.toLocal8Bit();
double d = atof(b.constData()) => 107.28
均做了四舍五入,造成精度丢失
解决方式 :
inline double strToDouble(const QString& strVal){
//such as "1.05e-5"
if(strVal.contains('e') || strVal.contains('E')){
int pos = strVal.indexOf('e');
if(pos<0){
pos = strVal.indexOf('E');
}
int z = strVal.mid(pos+1).toInt();
if(z<0){
return strToDouble(strVal.left(pos))/pow(10,-z);
}
else{
return strToDouble(strVal.left(pos))*pow(10,z);
}
}
else{
if(strVal.contains('.')){
int pos = strVal.indexOf('.');
int len = strVal.mid(pos+1).length();
return strVal.left(pos).toDouble()+strVal.mid(pos+1).toDouble()/powf(10,len);
}
else{
return strVal.toDouble();
}
}
}
更多推荐
所有评论(0)