W3docs

How to check if a String is numeric in Java

To check if a String is numeric in Java, you can use the isNumeric method of the StringUtils class from the org.apache.commons.lang3 library.

To check if a String is numeric in Java, you can use the isNumeric method of the StringUtils class from the org.apache.commons.lang3 library. Add the following dependency to your project:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Note that isNumeric only returns true if the string contains Unicode digits (0-9). It does not handle negative signs or decimal points.

Here's an example:


import org.apache.commons.lang3.StringUtils;

String str = "12345";
boolean isNumeric = StringUtils.isNumeric(str);

If the str variable contains only digits, the isNumeric variable will be true. Otherwise, it will be false.

You can also use the isCreatable method of the NumberUtils class from the same library to check if a String can be converted to a number. Unlike isNumeric, this method supports negative signs, decimal points, and scientific notation:


import org.apache.commons.lang3.math.NumberUtils;

String str = "12345";
boolean isCreatable = NumberUtils.isCreatable(str);

If the str variable contains a valid number representation, the isCreatable variable will be true. Otherwise, it will be false.

Alternatively, you can use the Double.parseDouble method to check if a String can be parsed to a double value. This approach requires no external dependencies:


String str = "12345";
boolean isNumeric = true;
try {
    Double.parseDouble(str);
} catch (NumberFormatException e) {
    isNumeric = false;
}

If the str variable contains a valid double representation, the isNumeric variable will be true. Otherwise, it will be false.