Click here to Skip to main content
15,921,884 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
double var1 = 123789456.785;
double var2 = 123789457.898;
double subtr = var2-var1;
qDebug()<<"Diff=>"<<subtr<<"Var1=>"<<var1<<"Var2=>"<<var2;

//Converting double to QString
QString str1 = QString::number(var1);
QString str2 = QString::number(var2);

//String to doubel
double newVar1= str1.toDouble();
double newVar2= str2.toDouble();
double subtrNew = newVar2-newVar1;
qDebug()<<"New Diff=>"<<subtrNew<<"New Var1=>"<<newVar1<<"New Var2=>"<<newVar2;


Output is this
Diff=> 1.113 Var1=> 1.23789e+08 Var2=> 1.23789e+08
New Diff=> 0 New Var1=> 1.23789e+08 New Var2=> 1.23789e+08


So after typecasting from Double to string than back from string to double i lost the difference which is 1.113. after type casting it becomes 0. how to tackle this issue. experts opinion is required. please.
Posted
Comments
Sergey Alexandrovich Kryukov 18-Dec-15 12:05pm    
Who told you there can be any reasonable type casting to string and back? What you do has nothing to do with casting.
If you have numeric data, why dealing with string at all? String should go only on output.
—SA
XamBEE 18-Dec-15 12:11pm    
while i am reading from .txt file this value(123789456.785) is in QStringList. I want to convert it to Double.

There is no type casting. You are just calling conversion functions.

Read the documentation of the used function QString::number(double)[^].

The function has two more optional parameters which have default values when not passed. The relevant parameter is the third one which defines the precision (the number of significand digits to be printed to the string). This is shown by your debug output:
Both string values have only 6 significand digits and are therefore identical.

You might now ask why the printed double values also have only 6 significand digits. It is for the same reason:
The stream << operator for double values uses also 6 significand digits when formatting the value. If you want more (or less) digits, you must specify the precision (with the C++ standard library it is std::setprecision()).

There are some general rules when printing floating point values to text files and reading them in later:

  • The max. required precision must be known.
  • Print values with the above precision plus one.
  • Use the 'g' format when printing to ensure that the precision is not lost for very large and small numbers.
  • Don't expect that the initial value that has been printed is binary identical to the one get back from string to double.
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900