I want to write a method which converts a decimal to the smallest possible numeric type without any data loss. For examples:
Convert(1)should return abyteConvert(257)should return ashortConvert(1.1)should return afloat- and so on
The input of the method is always a decimal and the output is any of the following .NET numeric types: sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.
I have tried using checked() to catch the OverflowException, however that approach doesn’t prevent loss. For example, checked((int)1.1) won’t throw any exception and return 1! Therefore, it’s not what I want.
Any recommendation?
Update: expected method signature
public object Convert(decimal d)
{
// return ...
}
you can try to use TryParse