Search code examples
c#mathdouble

Is there a method to find out if a double is a real number in C#?


So there is a method for NaN, but divide by zero creates infinity or negative infinity.

There is a method for Infinity (also positive infinite and negative infinity).

What I want is IsARealNumber function that returns true when the value is an expressible number.

Obviously I can write my own...

public bool IsARealNumber(double test)
{
    if (double.IsNaN(test)) return false;
    if (double.IsInfinity(test)) return false;
    return true;
}

but it doesn't seem like I should have to.


Solution

  • To add it as an extension method, it has to be a static member of a static class.

    public static class ExtensionMethods
    {
        public static bool IsARealNumber(this double test)
        {
            return !double.IsNaN(test) && !double.IsInfinity(test);
        }
    }