PDA

View Full Version : Wrong converting QVariant to double



estanisgeyer
2nd July 2009, 19:10
Hi,

I have to get a value from a database, for example, 2.3000. Must compare this value with the result of this calculation, as code:



QSqlQuery qry;
...
double y = 2.3;
double x = qry.value(0).toDouble(); // Take 2.30000 in the database, this example;

qDebug() << y << x; // Ok, show 2.3 value for x and y;

double z = x - y; // It's result in -2.66454e-15!

if (z < 0.00) {
...
}
else
{
...
}


If I make a calculation explicitly declare the values for the variables x and y, result is correct.
I created a method to convert a QString to a double that is working (code below). Any hint to resolve this as I use this function to work around the problem?



QSqlQuery qry;
...
double y = 2.3;
QString sx = qry.value(0).toString();

double x = myfunction->toDouble(sx);
double z = x - y; // It's OK, result 0
...


Thanks,

Marcelo Estanislau Geyer

wysota
2nd July 2009, 20:13
Never compare a double to a constant, especially if the double is a result of some calculations. Rely on a range instead.

double x = 2.3-q.value(0).toDouble();
if(qAbs(x)<=0.001){
// assume x==0
}

estanisgeyer
2nd July 2009, 20:42
Ok, for calculations in general, do not constantly have problems? For example:



QSqlQuery q;
...
double x = q.value(0).toDouble(); // Value is 2.3
double y = 2.0;
double z = x - z; // 0.3 "forever" ?



Thanks,

Marcelo Estanislau Geyer

wysota
2nd July 2009, 20:48
Double type can't represent any possible value, it uses approximations for the values it can't handle. If you perform operations on approximated values, the overall error increases. Never assume a calculated double is exactly what you expect it to be (remember it is a 64 bit value).

See for example the following link for details:
http://www.artima.com/underthehood/floating.html

jpn
15th July 2009, 22:19
See also qFuzzyCompare().