c++qt

Float to QString


I am facing some strange problem in floating point values. The following code displays a message box WITH decimal points. i.e., 10.53

QMessageBox Msgbox;
float num = 10.53;
QString str = QString::number(num, 'g', 4);
Msgbox.setText(str);
Msgbox.exec();

Where as the following code displays a message box WITHOUT decimal points. i.e., 1

QMessageBox Msgbox;
float num = 120/77;
QString str = QString::number(num, 'g', 4);
Msgbox.setText(str);
Msgbox.exec();

Why the digits after the decimal point are ignored in the second code snippet? I changed the data type to double and qreal. Nothing worked.


Solution

  • adding (float) before the numbers solved the issue. i.e., float num = (float)120/77;