I want to compare a number to its reference value, up to the precision of the reference.
If my reference has 2 decimals, I want to round the number to two decimals and then compare it with the reference.
If my reference is 7.95
:
7.942 is not OK
7.949 is OK
7.952 is OK
7.956 is not
I made my own function below, which works, but there maybe is something already available.
public bool IsEqual(double value, double reference)
{
var sReference = reference.ToString(System.Globalization.CultureInfo.InvariantCulture);
var decimals = sReference.Length - sReference.IndexOf('.') - 1;
return Math.Abs(reference - value) < Math.Pow(10, -decimals);
}
EDIT: I edited the question to make it more explicit.
- I don't need to set an epsilon, as it is set by the reference value precision. So all your kind suggestions of other topics that need to specify an epsilon do not apply to my need.
- I agree that using string conversion is not satisfying. Namely, large numbers represented in scientific notation don't work in my exemple. It's not my main focus for now, as i'm dealing with values like #.00 or #.000