The Matt
The Matt

Reputation: 6620

How to convert string to integer and determine if it's less than Int32.MinValue or greater than Int32.MaxValue?

I have the following piece of code which attempts to determine whether a given string is a valid integer. If it's an integer, but not within the valid range of Int32, I need to know specifically whether it's greater than Int32.MaxValue or less than Int32.MinValue.

try
{
     return System.Convert.ToInt32(input);
}
catch (OverflowException)
{
     return null;
}
catch (FormatException)
{
     return null;
}

Convert.ToInt32 will throw the OverflowException if it's not in the range of acceptable values, but it throws the same exception for both greater than and less than. Is there a way to determine which one it is aside from parsing out the text of the exception?

Upvotes: 1

Views: 3104

Answers (4)

Falanwe
Falanwe

Reputation: 4744

There is a very simple way to know if the input that threw an OverflowException (or gave a false if you used TryParse) is more than Int32.MaxValue or less than Int32.MinValue: a number less than Int32.MinValue will be a negative one, so its string representation will begin with a '-' !

Upvotes: 2

sll
sll

Reputation: 62564

The idea is:

bool isWrong = false;
bool isLarge = false;
if (!Int32.TryParse(rawValue, out int32Holder))
{
      if (!Int64.TryParse(rawValue, out int64Holder))
      {
           isWrong = true;
      }
      else
      {
           isLarge = true;
      }
}

Upvotes: 0

dlev
dlev

Reputation: 48606

You could convert it to Int64 (i.e. long) instead, and then do the comparison yourself. That will also eliminate an exception as control flow situation.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503839

As you're using .NET 4, you could use BigInteger - parse to that, and then compare the result with the BigInteger representations of int.MaxValue and int.MinValue.

However, I would urge you to use TryParse instead of catching an exception and using that for flow control.

Upvotes: 9

Related Questions