What is the correct way to convert a string to an unknown numeric type?
I am creating a type converter for use in a native library that should be able to convert from any type returned by the database (long, DBNull, bool, string, etc.). ) to any compatible type.
This all works fin and dandy for items that might be deprived:
try { return (T)value } catch(InvalidCaseException) { }
Or can be parsed:
see Convert to Nullable <T> from String using Reflection
However, I push the brick wall when I want this desired behavior:
Assert.That(
2,
Is.EqualTo(
Converter<long>.Convert("2.1")
));
The problem is that the Pasre and TryParse functions throw this back as an invalid format when the actual desired result is decimal truncation.
Do you think the best way to parse a string like "2.1" to an unknown value type is using reflection?
EDIT: I am currently using:
if (Nullable.GetUnderlyingType(t) != null)
{
t = Nullable.GetUnderlyingType(t);
}
MethodInfo parse = t.GetMethod("Parse", new Type[] { typeof(string) });
if (parse != null)
{
object parsed = parse.Invoke(null, new object[] { value.ToString() });
return (T)parsed;
}
else
{
throw new InvalidOperationException("The value you specified is not a valid " + typeof(T).ToString());
}
a source to share
What version of .NET and what is the range of values? One option, for example, would be to parse it as decimal and convert from it ...
T val = Convert.ChangeType(decimal.Parse("2.1"), typeof(T))
(the above just shows the central transformation - it doesn't try to fit it into existing code)
This won't work for huge / very small values, but it probably won't have the same rounding problems as double
.
a source to share