# C# – Comparing two decimals

c++comparisondecimal

I want to compare two decimals in c# with some margin of error. Can anyone point out problem with the following code. Note that I am interested in 6 decimal places after that I could ignore the values.

``````var valOne = decimal.Round(valueOne, 6);
var valTwo = decimal.Round(valueTwo, 6);
var difference = Math.Abs(valOne - valTwo);
if (difference > 0.0000001m) {
Console.WriteLine("Values are different");
}
else {
Console.WriteLine("Values are equal");
}
``````

or is there a better way.

#### Best Solution

If you are rounding the values to 6 decimal places, then your epsilon value is too small. The smallest amount the two values can differ is 0.000001.

For example:

``````var valOne = Decimal.Round(1.1234560M, 6);    // Gives 1.123456
var valTwo = Decimal.Round(1.1234569M, 6);    // Gives 1.123457

if (Math.Abs(valOne - valTwo) >= 0.000001M)
{
Console.WriteLine("Values differ");
}
else
{
Console.WriteLine("Values are the same");
}
``````