Best way to check if a Java String is a number.

One of the routine tasks in many Java applications is to convert a string to a number. For instance, you may have a form where user submits his or her age. The input will come to your Java application as a String but if you need the age to do some calculation you need to convert that String into a number.
Like,

   int age = new Integer(ageString).intValue();

But there is a possibility that the user might have entered an invalid number. Probably they entered “thirty” as their age.
If you try to convert “thirty” to a number you will get NumberFormatException. One way to avoid this is to catch and handle the NumberFormatException. But this is not the ideal and the most elegant solution to convert a string to a number in Java.

Another approach is to validate the input string before performing the conversion using Java regular expression. I like that second approach because it is more elegant and it will keep your code clean.

Here is how you can validate if a String value is numeric using Java regular expression.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
  /*A Java class to verify if a String variable is a number*/
  public class IsStringANumber{
	public static boolean isNumeric(String number){
         boolean isValid = false;
         /*Explaination:
            [-+]?: Can have an optional - or + sign at the beginning.
            [0-9]*: Can have any numbers of digits between 0 and 9
            \\.? : the digits may have an optional decimal point.
	    [0-9]+$: The string must have a digit at the end.
	    If you want to consider x. as a valid number change 
            the expression as follows. (but I treat this as an invalid number.).
           String expression = "[-+]?[0-9]*\\.?[0-9\\.]+$";
           */
           String expression = "[-+]?[0-9]*\\.?[0-9]+$";
           CharSequence inputStr = number;
           Pattern pattern = Pattern.compile(expression);
           Matcher matcher = pattern.matcher(inputStr);
           if(matcher.matches()){
              isValid = true;
           }
           return isValid;
         }
      }

The code above is self-explanatory. I explained the logic on how to build the regular expression to validate that a string has all numeric digits. I then use Matcher and Pattern classes to test the input string against the regular expression. If the input string passes the regular expression validation the method will return true, indicating that the string contains a numeric value. If the input string does not match the regular expression the method will return false.

Enjoy.!