This post will discuss how to check if a string is numeric or not in Java.

1. Using Double.parseDouble() method

A simple solution is to use the built-in methods of Java such as Double.parseDouble(), Double.valueOf(), or Float.parseFloat() to parse the string and see if it throws a NumberFormatException or not. We can enclose the method call within a try-catch block, and return true if no exception is thrown; false otherwise. To show how this works for different inputs, we have used the Double.parseDouble() method in the following program. This method parse the given string into a double, and throw a NumberFormatException if the string is not parsable.

Download  Run Code

2. Using Apache Commons Lang

We can also use external libraries such as Apache Commons Lang to check if a string is numeric. The isCreatable() method from the NumberUtils class checks whether the string is a valid Java number. The valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation, and numbers marked with a type qualifier.

Download Code

 
The advantage of using external libraries is that they may handle some edge cases or special formats that the built-in methods or regular expressions may not. For example, the NumberUtils.isCreatable() method can handle hexadecimal strings or strings with scientific notation.

3. Using Guava Library

With Guava, we can use the Double.tryParse() method to parse the specified string as a double. However, unlike the Double.parseDouble() method, it returns null instead of throwing an exception if parsing fails. The valid inputs are exactly those parsed by the Double.parseDouble() method, except that leading and trailing whitespace is not allowed.

Download Code

4. Using NumberFormat.parse() method

Another approach is to use the NumberFormat.parse() method to parse the given string. Unlike the Double.parseDouble() method, it does not throw an exception; if no object can be parsed, the index remains unchanged.

Download  Run Code

5. Using Regular Expression

Regular expressions can also be used to match the string against a pattern that allows only digits, decimal points, and optional signs. For example, the following program provides the regex-based solution using the regular expression [-+]?\d*\.?\d+ which handles the negative numbers and decimals. Note that \d matches only with the digits in range [0-9] but fail for digits in other languages.

Download  Run Code

6. Using Stream API

If we only care if the string is non-negative and non-decimal numbers, we can use Stream API. This is demonstrated below, where the solution only check if the string is a sequence of digits. Another such method is StringUtils.isNumeric() by Apache Commons Lang, which checks if a string contains only digits.

Download  Run Code

That’s all about checking if a string is numeric in Java.