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?
NullDev
7,3784 gold badges37 silver badges59 bronze badges
asked Feb 12, 2021 at 10:34
Karlos Garcia
1743 silver badges18 bronze badges
-
3Works fine for me; are you sure?Klaus Gütter– Klaus Gütter2021年02月12日 10:39:36 +00:00Commented Feb 12, 2021 at 10:39
-
1works for me.Guru Stron– Guru Stron2021年02月12日 10:41:41 +00:00Commented Feb 12, 2021 at 10:41
-
Try using decimal if double is not specifically required.TobyB– TobyB2021年02月12日 10:42:05 +00:00Commented Feb 12, 2021 at 10:42
-
I'm working with Visual Studio 17 and C#. It does not work for me. Condition "ImporteDebe==base1+Iva1" is never satisfied.Karlos Garcia– Karlos Garcia2021年02月12日 10:54:23 +00:00Commented Feb 12, 2021 at 10:54
-
With decimal variables works fine. Use decimal instead of double which implies in relation to executable? Size or speed of execution?Karlos Garcia– Karlos Garcia2021年02月12日 11:11:54 +00:00Commented Feb 12, 2021 at 11:11
1 Answer 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.");
answered Feb 12, 2021 at 10:43
ΦXocę 웃 Пepeúpa ツ
48.4k17 gold badges77 silver badges102 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Klaus Gütter
Very good advise in general, but the code in the question should still work as the values on both sides are calculated bit as
10.22 + 2.15Natalia Muray
But they might end up slightly different based on the CPU or the compiler used or even the build configuration. This answer is correct
lang-cs