-1

I have a float value that i parsed into double later i rounded off to 2.Also i have another float value to which i did exactly the same as first one. Here is the sample code..

string pulse = arrvaluedline[2].ToString();
pCost = float.Parse(arrvaluedline[3]);

double d = System.Convert.ToDouble(spCost);

double dd = Math.Round(d,2);

string[] arrpulse = pulse.Split(':');

vodanoofPulse = float.Parse(arrpulse[0]);

calculatedCost = CallCost * Pulse;

double dcalcost = Math.Round(calculatedCost, 2);

Now here i am trying to compare

 if (dcalcost.Equals(spCost)){
 }

Although my both values dcalcost and spCost are 0.4 Except this ,flow is not going inside the if ..Why..Please help me .,

user3725571
  • 55
  • 1
  • 2
  • 8

1 Answers1

4

The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .333333 and the Double value returned by dividing 1 by 3 are unequal.

// Initialize two doubles with apparently identical values 
double double1 = .33333;
double double2 = 1/3;
// Compare them for equality
Console.WriteLine(double1.Equals(double2));    // displays false

Comparing doubles are not as easy as one might think. Here is an example from MSDN on how you can do it in a better way.

// Initialize two doubles with apparently identical values 
double double1 = .333333;
double double2 = (double) 1/3;
// Define the tolerance for variation in their values 
double difference = Math.Abs(double1 * .00001);

if (Math.Abs(double1 - double2) <= difference)
   Console.WriteLine("double1 and double2 are equal.");
else
   Console.WriteLine("double1 and double2 are unequal.");
Karl-Henrik
  • 1,113
  • 1
  • 11
  • 17