Reputation: 3031
I have a function which takes two parameters and returns true if they are equal or false if they are not:
private bool isequal(object a, object b)
{
if (a != null)
return a.Equals(b);
if (b != null)
return b.Equals(a);
//if (a == null && b == null)
return true;
}
Now I want to extend this function. It should also return true if a and b are 2 equal numbers but of different type.
For example:
int a = 15;
double b = 15;
if (isequal(a,b)) //should be true; right now it's false
{ //...
}
I already found a similar question (with answer) best way to compare double and int but a and b could be any type of number or something else than numbers. How can I check if it a and b are numeric at all? I hope there is a better way than checking all existing numeric types of .net (Int32, Int16, Int64, UInt32, Double, Decimal, ...)
//update: I managed to write a method which works pretty well. However there might be some issues with numbers of the type decimal (have not tested it yet). But it works for every other numeric type (including high numbers of Int64 or UInt64). If anybody is interested: code for number equality
Upvotes: 5
Views: 7342
Reputation: 1738
You could use Double.TryParse on both a and b. It will handle int, long, etc.
private bool isequal(object a, object b)
{
if (a == null || b == null)
return (a == b);
double da, db;
if (Double.TryParse(a.ToString(), out da) && Double.TryParse(b.ToString(), out db))
return YourIsDoubleEqualEnough(da, db);
return false;
}
Upvotes: 5
Reputation: 322
try this
private bool isequal(object a, object b)
{
int c,d;
if (int.TryParse(a.ToString(), out c) && int.TryParse(b.ToString(), out d))
{
if (c == d)
return true;
}
if (a != null)
return a.Equals(b);
if (b != null)
return b.Equals(a);
//if (a == null && b == null)
return true;
}
Upvotes: 0