CString to double?????

  • Thread starter Thread starter Duncan Winn
  • Start date Start date
D

Duncan Winn

I am trying to convert a CString to a double using
atof()

however my nice CString of "0.58" gets converted to 0.579999223213147 etc

making it impossible to compare with a different double varaible of 0.58

Any suggestions on how to keep my origional value!!!!

Thanks

Ducnan
 
Ducnan:

Usually whenever you compare two different doubles/floats, you should use a
tolercance value (according your problem-set needs). That is, if both
doubles are within some tolerance of each other, for this problem, say 0.001
or 0.0001, then they are considered equivalent. This helps eliminate the
problems with rounding like you are seeing when you convert using atof().
So here would be a function to do this......

if (double_equiv(0.58, atof(arg), 0.001)) {
//THEY ARE EQUAL
}

bool double_equiv(double val1, double val2, double tolerance)
{
bool equiv=false;

if (fabs(val1 - val2)<=tolerance) {
equiv = true;
}
return equiv;
}

...Hope this helps....

-TGF
 
Duncan said:
I am trying to convert a CString to a double using
atof()

however my nice CString of "0.58" gets converted to 0.579999223213147 etc

making it impossible to compare with a different double varaible of 0.58

Any suggestions on how to keep my origional value!!!!

Thanks

Ducnan

It is not possible to keep your original value. Many numbers cannot be
represented exactly in binary floating point. Just like 1/3 cannot be
represented exactly in the decimal number system. The accuracy is very
good, but you must understand and deal with this awkward phenomenon in
every step.
 
If "0.58" represents £0.58, you might consider using something like
System.Decimal instead of a double: "The Decimal value type is appropriate
for financial calculations requiring large numbers of significant integral
and fractional digits and no round-off errors."

Dan
 
Back
Top