Since it can be any numeric type, you might want:
var i = decodedJson["key"];
bool isNumeric = i is byte || i is sbyte || i is short || i is ushort ||
i is int || i is uint || i is long || i is ulong ||
i is float || i is double || i is decimal;
if (isNumeric)
Convert.ToDecimal(i);
else
//handle
If you want to convert it to a type which is not the actual underlying type, a simple cast will not work. Convert
class has the comprehensive tests it would need.
Or make it generic all the way if you want:
public static T To<T>(this object source) where T : IConvertible
{
return (T)Convert.ChangeType(source, typeof(T));
}
public static bool IsNumeric(this Type t)
{
return t.In(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort),
typeof(int), typeof(uint), typeof(long), typeof(ulong),
typeof(float), typeof(double), typeof(decimal));
}
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Or find a more accurate version of IsNumeric
here.
So now you call:
var i = decodedJson["key"];
if (i.GetType().IsNumeric())
i.To<decimal>();
else
//handle