Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10025

Unbox a number to double

Does some way to cast an unknown number to double exists? For example

    public static double Foo(object obj)
    {
        if (!obj.GetType().IsValueType)
            throw new ArgumentException("Argument should be a number", "obj");
        return (double) obj;
    }

    private static void Main(string[] args)
    {
        double dbl = 10;
        decimal dec = 10;
        int i = 10;
        short s = 10;
        Foo(dbl);
        Foo(dec);
        Foo(i);
        Foo(s);
    }

but this code throws an Exception when trying to unbox to improper type.

Upvotes: 0

Views: 877

Answers (3)

W0lfw00ds
W0lfw00ds

Reputation: 2096

It's a fast way to use the Double.TryParse():

public static double Foo(object obj)
{
   double result;
   if (double.TryParse(obj.ToString(), out result))
      return result;
   else throw new ArgumentException("Argument should be a number", "obj");
}

Upvotes: 0

MRebai
MRebai

Reputation: 5474

Convert.ToDouble Method converts a specified value to a double-precision floating-point number.

public static double Foo(object obj)
    {
        return Convert.ToDouble(obj);
    }

Upvotes: 0

Tim S.
Tim S.

Reputation: 56546

The simplest way is probably to use Convert.ToDouble. This does the conversion for you, and works with numeric types, strings, and anything else that implements IConvertible (and has a value that can be converted to a double).

public static double Foo(object obj)
{
    // you could include a check (IsValueType, or whatever) like you have now,
    // but it's not generally necessary, and rejects things like valid strings
    return Convert.ToDouble(obj);
}

Upvotes: 10

Related Questions