If you’ve worked with variable whose datatypes are “double”, you may have seen a problem when you check if two doubles are equal.

The problem is the way that a double (also called “float”) variable is stored. Doubles sometimes lose accuracy.

So, a variable you think holds “1” actually holds “0.9999999999987423” – or something like that.

Here are two extension methods you can use to compare two double variables, and see if they are “equal enough”.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; namespace Engine { public static class ExtensionMethods { public static bool IsApproximatelyEqualTo(this double initialValue, double value) { return IsApproximatelyEqualTo(initialValue, value, 0.00001); } public static bool IsApproximatelyEqualTo(this double initialValue, double value, double maximumDifferenceAllowed) { // Handle comparisons of floating point values that may not be exactly the same return (Math.Abs(initialValue - value) < maximumDifferenceAllowed); } } } |

These functions subtract the second value from the first, get the absolute value (converting negative differences to a positive number), and check if the difference between the two numbers is less than a value you consider to be acceptable for declaring the variables “equal”.

Here is how you would use it in your code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public void Test() { double var1 = 1.0; double var2 = 9999999999987423; // Default level of accuracy if(var1.IsApproximatelyEqualTo(var2)) { // Do stuff } // Less restrictive level of accuracy if(var1.IsApproximatelyEqualTo(var2, 0.01)) { // Do other stuff } } |

The default value has always worked for the situations I’ve encountered, but you may see something different in your programs, and want to use your own level of accuracy.