Find your content:

Search form

You are here

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


I have a custom field called value__c in my custom object. This field can store values which could be a string, number, decimal or currency.

How can i check if this particular value can be converted to number,decimal or currency?


Attribution to: Prady

Possible Suggestion/Solution #1

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

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

Attribution to: techtrekker

Possible Suggestion/Solution #2

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

Attribution to: Doug B

Possible Suggestion/Solution #3

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

Attribution to: Douglas Hauck

Possible Suggestion/Solution #4

You can include the below class for your use. You can extend this for boolean, decimal. & datetime.

public class Convert{
    public class IntResult{
       public Boolean IsValid{ get; private set; }
       public Integer Value { get; private set; }
       public IntResult(Boolean pIsValid, Integer pValue){
           IsValid = pIsValid;
           Value = pValue;
       public IntResult(Boolean pIsValid){
           IsValid = pIsValid;
           Value = null;
    public static IntResult toInt(String strInput){
        IntResult result = null;
        try {
            Integer intValue = Integer.valueOf(strInput);
            result = new IntResult(true, intValue);
        Catch (exception e) {
            result = new IntResult(false);
        return result;
    static testmethod void testConvert_toInt() {
        IntResult res1 = Convert.toInt('34');
        IntResult res2 = Convert.toInt('we');
            System.debug('Invalid Value');

Attribution to: Gaurav Saxena
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content