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.
I think if I don't use Round then this solution is fine.
var valOne = 1.1234560M; // Decimal.Round(1.1234560M, 6); Don't round.
var valTwo = 1.1234569M; // Decimal.Round(1.1234569M, 6); Don't round
if (Math.Abs(valOne - valTwo) >= 0.000001M) // Six digits after decimal in epsilon
{
Console.WriteLine("Values differ");
}
else
{
Console.WriteLine("Values are the same");
}
As mentioned above for six decimal places the smallest amount the two decimals can differ is 0.000001M. Anything less than that can be safely ignored. I think this solution is fine but if anyone thinks I have missed something I appreciate your help.
Thanks all