How to check if a string is Numeric in Java?

How can I check if a String is a number e.g. “17” or “17.2”?

  1. Accepted Answer

Accepted Answer

Using Built-in Java Methods

The easiest way to do this is to use built-in methods in Java such as Double.parseDouble(String str). This method will return a double if the string argument is numeric and can be parsed to a number. If not, it’ll throw an exception. You could define a function like this:

/**
* Checks if the argument is numeric or not. Leading and trailing whitespace characters in str are ignored. Empty
* or null str return false.  For more info, see: https://codeahoy.com/q/11/
* @param str - the string to be checked
* @return true if the argument is numeric and can be parsed as a number. Returns false otherwise.
*/
public static boolean isNumeric(String str) {
    if (str == null) {
        return false;
    }
    try {
        Double.parseDouble(str);
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

Here’s how to use this method and some examples:

public static void main(String[] args) {
    System.out.println(isNumeric("17.2")); // true
    System.out.println(isNumeric("  17 ")); // true; leading and trailing whitespace are ignored
    System.out.println(isNumeric("-not-numeric-")); // false
}

If you only want to check if the string is integer or not, you can use Integer.parseInt(String str) instead.

Using Regular Expressions

Alternatively, you can also use a regular expression as well. The regex -?\\d+(\\.\\d+)? will work for positive, negative and decimal numbers.

  • -? this determines if the number starts with a minus sign (negative number.) The ? indicates that it is optional.
  • \d+ matches one or more digits
  • (\.\d+)? optionally match for decimal . and digits following it.
private static final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");

public static boolean isNumeric(String str) {
    if (str == null) {
        return false;
    }

    return pattern.matcher(str).matches();
}

Here’s how to use it:

public static void main(String[] args) {
    System.out.println(isNumeric("17.2")); // true
    System.out.println(isNumeric("-17.2")); // true
    System.out.println(isNumeric("-not-numeric-")); // false
}
Performance of Built-in vs Regular Expression

Generally, the Regex version will perform better than using built-in methods. It depends on the JVM, but usually this is because built-in relies on throwing and catching exceptions which is expensive.

On my machine, 10,000 samples (all arguments were valid integers) give the following benchmarks:

Built-in took 15 ms
Regex took 10 ms

If I introduce erroneous samples where every 2nd sample out of 10,000 is not a valid number, the numbers for built-in become worse as there’s a lot of exception handling going on.

Built-in took 35 ms
Regex took 11 ms

Using 3rd Party Libraries

You can also use Apache Common’s StringUtils.isNumeric() method:

public static boolean isNumeric(CharSequence cs)

Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false. Note that the method does not allow for a leading sign, either positive or negative. Also, if a String passes the numeric test, it may still generate a NumberFormatException when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range for int or long respectively.

Speak Your Mind