1

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
5
  • 3
    Works fine for me; are you sure? Commented Feb 12, 2021 at 10:39
  • 1
    works for me. Commented Feb 12, 2021 at 10:41
  • Try using decimal if double is not specifically required. Commented 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. Commented 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? Commented Feb 12, 2021 at 11:11

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.15
But they might end up slightly different based on the CPU or the compiler used or even the build configuration. This answer is correct

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.