一般情况下,QString toDouble是满足使用需求的。
不过也存在QString toDouble后,因为精度问题,会造成加减乘除、比较时,有时候因精度丢失,导致不准确。
现在把需要处理的double 放大10的N次方后,变成整数后,再进行相加相减处理,然后再缩小10的N次方倍。
代码如下:
//获取小数位
int getDecimalNum(QString str)
{
int n = str.indexOf(".");
if(n < 0)
{
n=0;
}
else
{
n = str.length()-n-1;
}
return n;
}
//获取放大后的字符串
QString getZoomIn(QString str,int n)
{
QString zoomStr;
int index = str.indexOf(".");
if(index < 0)
{
index=0;
zoomStr = str;
}
else
{
zoomStr+= str.left(index);
index = str.length()-index-1;
zoomStr += str.right(index);
}
for(int i=0; i < (n - index); i++)
zoomStr+="0";
return zoomStr;
};
//获取缩小后的字符串
QString getZoomOut(QString str,int n)
{
if(str.isEmpty())
return "";
QString zoomStr = str;
if(str.left(1) == "-")
{
zoomStr.remove(0,1);
}
if(n >0)
{
if(zoomStr.length() <= n)
{
int len = (n +1 - zoomStr.length() );
for(int i =0 ; i < len;i++)
zoomStr = "0"+zoomStr;
}
if(zoomStr.length() > n)
{
int index = zoomStr.length()-n;
zoomStr.insert(index,".");
for(int i =0 ;i < zoomStr.length(); i++)
{
index = zoomStr.length()-1- i;
if(index < 0)
break;
if(zoomStr.mid(index,1) == "0")
{
zoomStr.remove(index,1);
i--;
}
else if(zoomStr.mid(index,1) == ".")
{
zoomStr.remove(index,1);
break;
}
else
{
break;
}
}
}
}
if(str.left(1) == "-")
{
zoomStr.insert(0,"-");
}
return zoomStr;
};
//两个double字符串相加
QString addDoubleStr(QString t1,QString t2)
{
int n = qMax(getDecimalNum(t1),getDecimalNum(t2));
QString zoomStr = QString::number((getZoomIn(t1,n).toInt()+ getZoomIn(t2,n).toInt()));//放大到变成整数后相加
zoomStr = getZoomOut(zoomStr,n);//再缩小回去
return zoomStr ;
}
//两个double字符串相减
QString subtractDoubleStr(QString t1,QString t2)
{
int n = qMax(getDecimalNum(t1),getDecimalNum(t2));
int d1 = getZoomIn(t1,n).toInt() ;//放大到变成整数后
int d2 = getZoomIn(t2,n).toInt() ;
QString zoomStr;
if(d1 == d2)
return "0";
else
{
zoomStr = QString::number((d1-d2));
}
zoomStr = getZoomOut(zoomStr,n);//再缩小回去
return zoomStr;
}
例子:
//转换
void MainWindow::on_pushButton_clicked()
{
ui->textEdit->clear();
QString t1 = ui->lineEdit->text();
QString t2 =ui->lineEdit_2->text();
ui->lineEdit_3->setText(subtractDoubleStr(t1,t2));
ui->lineEdit_4->setText(addDoubleStr(t1,t2));
int n1 = getDecimalNum(t1);
int n2 = getDecimalNum(t2);
int n = qMax(n1,n2);
int zoom = qPow(10,n);
ui->textEdit->append(QString("t1=%1,小数位=%2").arg(t1).arg(n1));
ui->textEdit->append(QString("t2=%1,小数位=%2").arg(t2).arg(n2));
ui->textEdit->append(QString("最大小数位=%1,倍数=%2").arg(n).arg(zoom));
int d1 = getZoomIn(t1,n).toInt();
int d2 = getZoomIn(t2,n).toInt();
ui->textEdit->append(QString("放大后 t1=%1,t2=%2").arg(d1).arg(d2));
QString t3 =ui->lineEdit_5->text();
QString t4 = subtractDoubleStr(addDoubleStr(t1,t2),t3);
double d4 = t4.toDouble();
ui->textEdit->append(QString("(t1+t2) -t3 = %1").arg(d4));
ui->textEdit->append(QString("%1 + %2 %3 %4").arg(t1).arg(t2).arg((d4==0?"=":(d4>0?">":"<"))).arg(t3));
qDebug() << t1 << t2 << t3 << t4 ;
}