Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two decimals

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.

like image 676
tangokhi Avatar asked Jun 09 '15 08:06

tangokhi


1 Answers

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");
}
like image 169
Dave R. Avatar answered Oct 04 '22 03:10

Dave R.