C# Tip – How to check if two double values are equal

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”.

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *