如: 

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

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐