从double转换为decimal时避免OverflowException

时间:2016-11-04 09:20:53

标签: c# exception floating-point overflowexception

double(或float)转换为decimal时,可能会出现溢出异常。所以我写了这个小扩展方法,通过饱和来防止这种情况:

public static decimal ToDecimalSafe(this double input)
{
    try
    {
        return (decimal)input;
    }
    catch (OverflowException)
    {
        if (input < 0)
            return decimal.MinValue;
        else
            return decimal.MaxValue;
    }
}

问题是,这种溢出经常发生在我的用例中,打破了#34;异常应该是特殊的&#34;指南。这会减慢应用程序的速度,是的,但这并不是非常重要。真正的问题是它在调试过程中也会导致大量的第一次机会异常,这很烦人。这是第二次尝试,似乎工作正常:

public static decimal ToDecimalSafe(this double input)
{
    if (input < (double)decimal.MinValue)
        return decimal.MinValue;
    if (input > (double)decimal.MaxValue)
        return decimal.MaxValue;

    try
    {
        return (decimal)input;
    }
    catch (OverflowException)
    {
        if (input < 0)
            return decimal.MinValue;
        else
            return decimal.MaxValue;
    }
}

我离开了try-catch,以确保我抓住了一些可能的边缘情况。这里的问题是:是否有任何边缘情况或者我可以省略try-catch?

double可以>= (double)decimal.MinValue<= (double)decimal.MaxValue并且在转换时仍会导致溢出吗?

1 个答案:

答案 0 :(得分:1)

不再发生异常。您可以通过这种方式修改代码。

public static decimal ToDecimalSafe(this double input)
{
    if (input < (double)decimal.MinValue)
        return decimal.MinValue;
    else if (input > (double)decimal.MaxValue)
        return decimal.MaxValue;
    else
        return (decimal)input;
}

您也可以使用特定的转换方法,但不会阻止异常

Convert.ToDecimal

如果您的问题只是令人讨厌的调试中断,那么我建议您查看[DebuggerStepThrough]或[DebuggerHidden]属性