PDA

View Full Version : float value incorrect when read back



babygal
16th June 2010, 08:18
Float value incorrect when read back.
The value is first read as string then converted to float.
The float value is converted back to string and the value is read back.The value read back is incorrect! :-(

Here is the code:



void function(const float);
QLineEdit *stringText;
QString string,floatintostring ;

stringText->setText(string); //1.read as string

function(string.toFloat() ); //2.convert string into float

floatintostring = QString::number(string.toFloat()); //3.convert float into string

QMessageBox::about(this,tr("Show float value"),floatintostring);//4.float value read back and value shown is incorrect

high_flyer
16th June 2010, 08:23
Can you show what is the value written, and what you get back?

babygal
16th June 2010, 08:33
Can you show what is the value written, and what you get back?


Value written: 1.234
Value read back : 0

high_flyer
16th June 2010, 08:44
Wait a minute...
do you use this code to READ the number??


stringText->setText(string);


Where is 'string' defined?

babygal
16th June 2010, 09:05
Wait a minute...
do you use this code to READ the number??


stringText->setText(string);


Where is 'string' defined?

Yes, i use the code to read the number.

Sorry here is the definition of string and floatintostring :

QString string,floatintostring ;

ChrisW67
16th June 2010, 09:09
You are putting the string INTO the QLineEdit with that line. "string" is a null or empty (not sure which) QString. When interpreted as a float it is 0.

babygal
16th June 2010, 11:14
You are putting the string INTO the QLineEdit with that line. "string" is a null or empty (not sure which) QString. When interpreted as a float it is 0.
So that line is causing the error? How to solve?

high_flyer
16th June 2010, 11:34
How to solve?
Learn C++.

wysota
16th June 2010, 17:08
Well... the only thing this code should do is crash at line #5...

babygal
17th June 2010, 02:52
it doesn't crash..just that the value read back is incorrect.

babygal
17th June 2010, 04:31
SOLVED! :D
Here is the solution:


void function(const float);
QLineEdit *stringText;
QString string,floatintostring ;

//stringText->setText(string); //1.read as string (removed)

function(stringText->text().toFloat() ); //2.convert string into float

floatintostring = QString::number(stringText->text().toFloat() ); //3.convert float into string

QMessageBox::about(this,tr("Show float value"),floatintostring);//4.float value read back and value shown is correct

Use text() to retrieve the entered text and it works! :D

agathiyaa
17th June 2010, 12:11
Please take a crash course on C++