Karlos Garcia
Karlos Garcia

Reputation: 174

precision in variables

I have problems with the precision of the variables when performing calculations and comparing the results. I am working in C #. Here is an example.

double ImporteDebe;
ImporteDebe = 0;
double base1;
base1 = Convert.ToDouble("10,22");
double PorcentajeIva1;
PorcentajeIva1 = Convert.ToDouble("0,21");
double Iva1;
Iva1 = Convert.ToDouble((base1 * PorcentajeIva1).ToString("N2")); //2,1462 -> 2,15

ImporteDebe = ImporteDebe + base1; // 10,22
ImporteDebe = ImporteDebe + Iva1;// 10,22 + 2,15 = 12,37000000001

if (ImporteDebe == (base1 + Iva1))
{
    System.Diagnostics.Debug.Print(Convert.ToString(ImporteDebe));//condition is never met
}

if you run the code you see that the condition "ImporteDebe == (base1 + Iva1)" is never met

Does the problem have a simple solution?

Upvotes: 1

Views: 51

Answers (1)

you should not compare doubles using the == operator

but instead like in the official doc here:

// 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);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(double1 - double2) <= difference)
   Console.WriteLine("double1 and double2 are equal.");
else
   Console.WriteLine("double1 and double2 are unequal.");

Upvotes: 3

Related Questions