Superman
Superman

Reputation: 3784

C# converting a decimal to an int safely

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?

Upvotes: 11

Views: 5822

Answers (5)

mattypiper
mattypiper

Reputation: 1232

Why are you trying to avoid catching the OverflowException? It is there for a reason and you should totally catch it where you call Decimal.ToInt32(). Exceptions are used widely throughout the framework and users should catch them. The Try methods can help you around them to make code tighter and cleaner, but where the framework doesn't have a suitable method (Decimal.TryConvertToInt32() in this case) catching OverflowException is the appropriate thing to do. It is actually more clear than making an extension class or writing your own separate static method (both of those involve writing your own code where the framework is already giving you this functionality).

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

What's wrong with using Int32.TryParse(string) ?

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

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());
}

Upvotes: 4

Oded
Oded

Reputation: 499052

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;
}

Upvotes: 11

Anthony Pegram
Anthony Pegram

Reputation: 126884

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

Upvotes: 2

Related Questions