0

I tried this code but still have problem for QString to short value for example it work well for text = 20 but it return 0 for value = 20.5.

but I need value=20. how can I solve it?

inline __int16 GetStaticToInteger(QLineEdit* lineEdit) {
    QString text; __int16 nValue = 0;
    nValue = QString::number(lineEdit->text().toDouble()).toShort();
    return nValue;
}
citi
  • 31
  • 2
  • 7
  • This is a duplicate of http://stackoverflow.com/questions/21133389/qstring-to-short-using-toshort – RobbieE Jan 15 '14 at 18:17

2 Answers2

2

'20.5' is not a valid text representation for an integer value. You can check this:

QString str("20.5");

bool ok;
short s = str.toShort(&ok);

qDebug() << ok

The output will be 'false'.

If you need an integer value you can do this:

short s = str.toDouble();

If you need your value rounded to the nearest integer use qRound:

short s = qRound(str.toDouble());
hank
  • 9,553
  • 3
  • 35
  • 50
1

You have made it to complicated.

inline __int16 GetInteger16FromStatic(QLineEdit* lineEdit) {
    QString text; __int16 nValue = qRound(lineEdit->text().toDouble());
    return nValue;
}

Also Qt provides types with defined size, like qint16 to be compiler/platform independent, so you don't have to use __int16.

Marek R
  • 32,568
  • 6
  • 55
  • 140