简体   繁体   中英

QT: Float to QString

I am new to QT. I am facing some strange problem in floating point values. The following code displays a message box WITH decimal points. ie, 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. ie, 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.

because 120/77 is dividing 2 integers (resulting in a integer) and then converting to float

you need to convert the numbers to float before dividing

float a = 120, b = 77;
float num = a/b;

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

float num = 120.0/77.0;

也可以,对于C来说是标准的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM