Last Updated:

Is the string a number [ Java ]

In this article, we'll learn how to check to see if a given string is a number. We'll look at a few ways: using external libraries and using the standard JavaSE API.

Method 1: Check if the string is a number (Java API)

 

Here we use only the standard JavaSE API. In the first option, we try to cast the string to the Double type, and if we succeed, we consider that the specified string is a number:

 

public static boolean isNumeric(String str) {
try {
Double. parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}

With this method, you can check integers, fractional numbers, numbers with a leading plus or minus sign.

Method 2: Check if the string is a number (Apache Commons)

 

In this way, we use the Apache Commons library. If you have a Maven project, specify the following artifact in your pom.xml file:

 

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

Using the NumberUtils.isParsable method, we can check whether the specified string is a number:

 

System. out. println(NumberUtils. isParsable("120.99")); // true
System. out. println(NumberUtils. isParsable("+120.99f")); // true
System. out. println(NumberUtils. isParsable("-120.99f")); // true
System. out. println(NumberUtils. isParsable("120.99abc")); // false
System. out. println(NumberUtils. isParsable("0xFF")); // false
 

The isParsable method is a wrapper over Integer.parseInt, Long.parseLong, Float.parseFloat, and Double.parseDouble. It is convenient to use it in order not to write template code for catching exceptions of these methods.

 

Source code

 

isstringnumber1.java
public class IsStringNumber1 {
 
public static void main(String[] args) {
System. out. println(isNumeric("120.99")); // true
System. out. println(isNumeric("+120.99f")); // true
System. out. println(isNumeric("-120.99")); // true
System. out. println(isNumeric("120.99abc")); // false
System. out. println(isNumeric("0xFF")); // false
}
 
public static boolean isNumeric(String str) {
try {
Double. parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
isstringnumber2.java
import org. apache. commons. lang3. math. NumberUtils;
 
public class IsStringNumber2 {
 
public static void main(String[] args) {
System. out. println(NumberUtils. isParsable("120.99")); // true
System. out. println(NumberUtils. isParsable("+120.99f")); // true
System. out. println(NumberUtils. isParsable("-120.99f")); // true
System. out. println(NumberUtils. isParsable("120.99abc")); // false
System. out. println(NumberUtils. isParsable("0xFF")); // false
}
}

Conclusion

 

We've looked at different ways to test a string for whether it's a number.