Is there any method to check the POSSIBILITY of converting a string to an Integer type

apex

Is there any way or method to check the POSSIBILITY of converting a string to an Integer type, or in other words: how do I know if an exception will be thrown when converting a string to an Integer? My idea is to use a try/catch block, and I want to know if there is a less cumbersome way. In Apex Salesforce!

Here is my code, are there any more accurate analogues:

public static boolean isConvertPoss(string str)
    {
            try
            {
                integer number=Integer.valueOf(str);
            }
            catch(Exception e)
            {
                return false;
            }
            return true;
}

Best Answer

If you want to avoid the possible expense of throwing an exception, you can use a Pattern (regular expression):

public static boolean isConvertPoss(string str)
  if(str != null) {
    Pattern p = Pattern.compile('[-+]?\\d{1,10}');
    try {
      return p.matcher(str).matches() && Integer.valueOf(str) != null;
    } catch(Exception e) {
      return false;
    }
  }
  return false;
}

We first check if str is not null, then we create a pattern that allows a optional leading positive/negative indicator followed by at least one digit.

Edit: based on comments, I realized we should probably do a sanity check that there are no more than ten digits, and afterwards try a conversion in case it's outside the binary range of -231 to 231-1.

Related Topic