0

I have seen this behavior when I try adding double values where one of the value is a negative double, the order in which I add these values apparently does matter. Here's my test

    double val1 = -0.06, val2 = 0.04, val3 = 0.02;
    double resOrder1 = val1 + val2 + val3;
    double resOrder2 = val2 + val3 + val1;
    Console.WriteLine(resOrder1); //3.46944695195361E-18
    Console.WriteLine(resOrder2); //0

Am I missing some key principle here? Moreover, how do I make sure I get true for if(resOrder1 == 0){} regardless the addition order. And no I don't want to change the data type to decimal.

Talha
  • 107
  • 9
  • 3
    [What every computer scientist should know about floating-point arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Matthew Watson Nov 29 '17 at 14:18
  • 4
    That's because not all double values can be represented exactly. That's why you should test doubles against a tolerance range instead of an exact value. – juharr Nov 29 '17 at 14:18
  • Also https://stackoverflow.com/a/7936044/106159 – Matthew Watson Nov 29 '17 at 14:19

0 Answers0