I've got a method like this:
public static bool IsPercentage<T>(T value) where T : IComparable
{
return value.CompareTo(0) >= 0 && value.CompareTo(1) <= 0;
}
I would like to use this to validate if any number falls in the range 0 <= N <= 1. However this only works with integers since CompareTo only operates on equal types. Is there a different way to do this?
well you could use Convert.ToDecimal
, then you don't need to be generic:
public static bool IsPercentage(Object value)
{
decimal val = 0;
try
{
val = Convert.ToDecimal(value);
}
catch
{
return false;
}
return val >= 0m && val <= 1m;
}