Reputation: 5758
I have a 'QString' containing "-3.5", however if I try to convert this to an integer using the 'toInt' method it returns 0. Why?
QString strTest = "-3.5";
int intTest = strTest.toInt();
qDebug() << intTest;
intTest will be 0 ?
Upvotes: 3
Views: 8363
Reputation: 16421
As opposed to std::stoi
and streams from the standard library, Qt strings require the whole string to be a valid integer to perform the conversion. You could use toDouble
instead as a workaround.
You should also use the optional ok
parameter to check for errors:
QString strTest = "-3.5";
book ok;
int intTest = strTest.toInt(&ok);
if(ok) {
qDebug() << intTest;
} else {
qDebug() << "failed to read the string";
}
Upvotes: 6
Reputation: 76297
If you look at the documentation, it says
Returns 0 if the conversion fails.
You should use
bool ok;
strTest.toInt(&ok);
and then check the value of ok
- otherwise, you won't be sure if the 0 is the actual value, or an indication of failure.
In this case it's failing because it is not actually an integer (it has a decimal point). Note that you can use toDouble
(and check ok
there too!), and then cast the result as you see fit.
QString strTest = "-3.5";
bool ok;
double t = strTest.toDouble(&ok);
if(ok)
qDebug() << static_cast<int>(t);
Upvotes: 5