PDA

View Full Version : QString to double convertion problem



NoRulez
7th July 2010, 13:24
Hi @all,

i have a QLineEdit and want the text converted to a double, so I do:


lineEdit->setText("123456789");
QVariant val = lineEdit->text().toDouble();
qDebug() << val;
.
.
.
lineEdit2->setText(val.toString());

Now the output would be: QVariant(double, 1.23457e+08)
And also the value in lineEdit2 is "1.23457e+08"

How can I avoid the exponentials?

Thanks in advance

Best Regards
NoRulez

borisbn
7th July 2010, 15:28
lineEdit->setText("123456789");
QVariant val = lineEdit->text().toDouble();
qDebug() << val; // <--- QDebug::operator<< can't format doubles as 123.45
.
.
.
const int precision = 2;
lineEdit2->setText( QString( "%1 ).arg( val.toDouble(), 0, 'f', precision ) );

ChrisW67
7th July 2010, 23:00
Don't rely on the default behaviour of QVariant::toString() if you don't like its output. As a variation to borisbn's approach, you could use QString::number() and choose the 'f' format and a number desired figures after the decimal point.
BTW: If you want to convert to a double why do you convert to a QVariant?



lineEdit->setText("12345678");
bool ok;
double d = lineEdit->text().toDouble(&ok);
if (ok) {
qDebug() << QString::number(d, 'f', 6);
qDebug() << QString::number(d, 'f', 2);
qDebug() << QString::number(d, 'f', 0);
}

NoRulez
9th July 2010, 18:48
@ChrisW67: Because the QVariant is in my example a model