Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# converting a decimal to an int safely

Tags:

c#

decimal

I am trying to convert a decimal to an integer safely.

Something like

public static bool Decimal.TryConvertToInt32(decimal val, out int val)

this will return false if it cannot convert to an integer, and true w/ successful output if it can.

This is to avoid catching the OverflowException in decimal.ToInt32 method. What is the easiest way to do this?

like image 351
Superman Avatar asked Nov 30 '11 14:11

Superman


3 Answers

I would write an extension method for class decimal like this:

public static class Extensions
{
    public static bool TryConvertToInt32(this decimal decimalValue, out int intValue)
    {
        intValue = 0;
        if ((decimalValue >= int.MinValue) && (decimalValue <= int.MaxValue))
        {
            intValue = Convert.ToInt32(decimalValue);
            return true;
        }
        return false;
    }
}

You can use it in that way:

if (decimalNumber.TryConvertToInt32(out intValue))
{
    Debug.WriteLine(intValue.ToString());
}
like image 178
Fischermaen Avatar answered Nov 08 '22 22:11

Fischermaen


Here:

public static bool TryConvertToInt32(decimal val, out int intval)
{
    if (val > int.MaxValue || val < int.MinValue)
    {
      intval = 0; // assignment required for out parameter
      return false;
    }

    intval = Decimal.ToInt32(val);

    return true;
}
like image 23
Oded Avatar answered Nov 08 '22 23:11

Oded


Compare the decimal against int.MinValue and int.MaxValue prior to the conversion.

like image 2
Anthony Pegram Avatar answered Nov 08 '22 22:11

Anthony Pegram