function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Prachi SPrachi S 

How to check if input string is valid decimal same way isNumeric checks input string is valid integer number?

Hi All,

In my apex code I need to check if an input string from CSV file is a valid number. It can be a integer or decimal value.
isNumeric only returns true if the input is integer but does not work for decimal.
Is there an easy way to determine if an input string from CSV file is a valid decimal or integer ?
 
String numeric = '1234567890';
system.debug(numeric.isNumeric());


String decimalPoint = '1.2';
system.debug(decimalPoint.isNumeric());

Logs Displays:

true
flase


 
Best Answer chosen by Prachi S
Arunkumar RArunkumar R
Hi Prachi,

You can check like below,
String decimalPoint = '1.23';
Boolean isValidDecimal = true;
if(decimalPoint != null){
    try{
        Decimal.valueOf(decimalPoint);
    }
    catch(TypeException e){
       isValidDecimal = false; 
    }
}
system.debug(isValidDecimal);

All Answers

Arunkumar RArunkumar R
Hi Prachi,

You can check like below,
String decimalPoint = '1.23';
Boolean isValidDecimal = true;
if(decimalPoint != null){
    try{
        Decimal.valueOf(decimalPoint);
    }
    catch(TypeException e){
       isValidDecimal = false; 
    }
}
system.debug(isValidDecimal);
This was selected as the best answer
Prachi SPrachi S
That works like a charm. Thank you!