将十进制转换为可能的最小数字类型,而不会丢失任何数据

时间:2011-05-14 09:56:08

标签: c# .net

我想编写一个方法,将decimal转换为尽可能小的数字类型而不会丢失任何数据。例如:

  • Convert(1)应返回byte
  • Convert(257)应返回short
  • Convert(1.1)应返回float

方法的输入始终为decimal,输出为以下任何.NET数值类型:sbytebyteshort,{{1 },ushortintuintlongulongfloatdouble

我尝试使用decimal来捕获checked(),但这种做法并不能防止丢失。例如,OverflowException不会抛出任何异常并返回checked((int)1.1)!因此,这不是我想要的。

任何建议?

更新:预期的方法签名

1

2 个答案:

答案 0 :(得分:1)

您可以尝试使用TryParse

        short res;
        decimal value = 8913798132;
        bool s = short.TryParse(value.ToString(), out res); // returns false

答案 1 :(得分:1)

这就是我最终要做的事情。可以使用一些反射来减少代码量 - 但是由于这种方法在我的应用程序中被调用了很多次,所以我觉得这样更好。

private static object NarrowNumber(decimal value)
{
    decimal wholePart = Math.Truncate(value);
    if (value == wholePart)
    {
        if (sbyte.MinValue <= wholePart && wholePart <= sbyte.MaxValue)
            return (sbyte)wholePart;
        if (byte.MinValue <= wholePart && wholePart <= byte.MaxValue)
            return (byte)wholePart;
        if (short.MinValue <= wholePart && wholePart <= short.MaxValue)
            return (short)wholePart;
        if (ushort.MinValue <= wholePart && wholePart <= ushort.MaxValue)
            return (ushort)wholePart;
        if (int.MinValue <= wholePart && wholePart <= int.MaxValue)
            return (int)wholePart;
        if (uint.MinValue <= wholePart && wholePart <= uint.MaxValue)
            return (uint)wholePart;
        if (long.MinValue <= wholePart && wholePart <= long.MaxValue)
            return (long)wholePart;
        if (ulong.MinValue <= wholePart && wholePart <= ulong.MaxValue)
            return (ulong)wholePart;
    }
    else
    {
        var strValue = value.ToString();
        float f;
        if (float.TryParse(strValue, out f))
            return f;
        double d;
        if (double.TryParse(strValue, out d))
            return d;
    }
    return value;
}