PDA

View Full Version : QSqlQuery and rounding off of data



ShamusVW
16th May 2016, 09:09
I have created a QSqlQuery to access a MySQL database.
When I run the query against the database, it rounds to required 2 digits, however the QSqlQuery returns 17 digits.
Any idea why this happens? I don't necessarily want to format the returned value, I want the database to return the formatted value, hence I include it in the query.

This is my query... (and following that is my function to access the database)
The 2 fields returned are supposed to be 0.26 & 0.46.
Instead I get 0.26000000000000001 & 0.46000000000000002


SELECT ROUND(c1/TIME_TO_SEC(TIMEDIFF(now(), '2016/05/16 06:00:00')),2) AS p1,
ROUND(c2/TIME_TO_SEC(TIMEDIFF(now(), '2016/05/16 06:00:00')),2) AS p2 FROM
(SELECT SUM(TIME_TO_SEC(TIMEDIFF(cycle_end, cycle_start))) AS c1 FROM daq_iv.dae005_cycles WHERE pallet_no = 1 AND cycle_start >= '2016/05/16 06:00:00')t1,
(SELECT SUM(TIME_TO_SEC(TIMEDIFF(cycle_end, cycle_start))) AS c2 FROM daq_iv.dae005_cycles WHERE pallet_no = 2 AND cycle_start >= '2016/05/16 06:00:00')t2


QStringList DBMySQL::getData(QString queryString)
{
QStringList sl;
if (m_DBOpen) {
QSqlQuery query(QSqlDatabase::database(m_ConnectionName)); //create QSqlQuery object using given database
query.setForwardOnly(true); //sets mode to traverse forwards only through result set, potentially improves speed
if (!(query.exec(queryString))) { //if succesful, returns true else false
sl << query.lastError().text(); //error executing query, return the error
}
else {
int fieldCount = query.record().count();
while (query.next()) {
QString str("");
for (int i = 1; i <= fieldCount ; ++i) { //return each row as a comma deliminated string
if (i == fieldCount)
str = str + query.value(i-1).toString();
else
str = str + query.value(i-1).toString() + "|";
}
sl << str;
}
}
}
else {
sl << "DB not open";
}
return sl;
}

anda_skoa
16th May 2016, 10:41
My guess would be that "ROUND" just rounds the value and does not convert it to a string.
So the type of the value is still a floating point number and the values you get are the closest possible to the rounded values.

Again assuming that ROUND does not create a string, then that is missing from your query.

Cheers,
_

ShamusVW
16th May 2016, 12:54
That makes sense.
I formatted it in my code anyway now, so doesn't matter anymore.
Thanks for the reply.