Is there a function to check if a string value be converted to number?

You can use some of the new String methods, for example isNumeric.
Are you in a situation where you don't know in advance what kind of data will be in the string? You can use try and catch around attempted conversions, eg.

try {
  Integer x = Integer.valueOf(myString);
}
Catch (exception e) {
  // it's not an Integer, try something else
}

You can use the Integer.valueOf and the instanceof constructs to achieve this (primitives also being objects in apex helps !)

    try{
    object  m = Integer.valueOf('123');
    System.debug(m instanceof integer);   //returns true if integer, false otherwise
    }
    catch(Exception e){
        // if not integer
    }

I don't know about Apex, but in most languages, try/catch blocks are not efficient to run (they have a lot of processor overhead). So if(test) methods are generally preferable to try/catch methods, especially inside a loop.

I know Apex doesn't have an isNumeric() method that recognizes the decimal point, but we can use the replaceFirst() method to remove just a single decimal point, then run isNumeric() on the remaining string:

if(myString.replaceFirst('.', '').isNumeric())
    myDecimal = decimal.valueOf(myString);

Tags:

Apex

Trigger