Comparing two "Double" variables with -eq/-ne does not validate if number is creater than 2 digits Comparing two "Double" variables with -eq/-ne does not validate if number is creater than 2 digits powershell powershell

Comparing two "Double" variables with -eq/-ne does not validate if number is creater than 2 digits


Note that this isn't an issue with Powershell, it's simply a problem that exists with floating point arithmetic. You can reproduce the same behavior in C#

double d = 336.1;Console.WriteLine((d + .1) == 336.2); // False

The problem is that 336.1 + .1 is not actually equal to 336.2. You can prove this by dumping the raw bytes for the 2 values

 unsafe {    double d1 = 336.1;    double d2 = d + .1d;    double d3 = 336.2;    Console.WriteLine(*(long*)(&d2));    Console.WriteLine(*(long*)(&d3)); }

Prints

46446221091397435404644622109139743539

Notice that the last 2 bytes are off by 1 value. As to why this is the case someone who deals more with floating point arithmetic would have to say. In general though you should be careful when comparing floating point values. Instead of strict equality it's better to check that they are within a specific range

if (Math.Abs(d2 - d3) <= .01)) {  ...}