0

I want to convert QString to short.when I try this code

ui->lineEdit->text().toShort();

It works well for text = 20 but it returns "0" for value = 20.5.

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

Maxim Makhun
  • 2,197
  • 1
  • 22
  • 26
citi
  • 31
  • 2
  • 7
  • don't allow decimal points in the lineEdit – ratchet freak Jan 15 '14 at 09:28
  • QString::number(ui->lineEdit->text().toInt()).toShort(); – Shf Jan 15 '14 at 09:38
  • I tried this code but still have problem inline __int16 GetInteger16FromStatic(QLineEdit* lineEdit) { QString text; __int16 nValue = 0; nValue = QString::number(lineEdit->text().toDouble()).toShort(); return nValue; } – citi Jan 15 '14 at 09:59

2 Answers2

4

The reason that 0 is returned is because a decimal point is an invalid character for the short data type.

If you want to be able to convert floating-point numbers from QString to integers, you need to convert your text to a float or double first, then use normal rounding/truncation to convert to short.

RobbieE
  • 4,280
  • 3
  • 22
  • 36
0

use that convertion string:

ui->lineEdit->text()->split(".")[0].toShort(0,10);
kazak1377
  • 21
  • 5