Java: Check if String is a Number

Introduction

Strings are a handy way of getting information across and getting input from a user.

In this article, we will go through a couple of ways check if a String is Numeric in Java - that is to say, if a String represents a numeric value.

Check if String is Numeric with Core Java

Users tend to mistype input values fairly often, which is why developers have to hold their hand as much as possible during IO operations.

The easiest way of checking if a String is a numeric or not is by using one of the following built-in Java methods:

  1. Integer.parseInt()
  2. Integer.valueOf()
  3. Double.parseDouble()
  4. Float.parseFloat()
  5. Long.parseLong()

These methods convert a given String into its numeric equivalent. If they can't convert it, a NumberFormatException is thrown, indicating that the String wasn't numeric.

It's worth noting that Integer.valueOf() returns a new Integer(), while Integer.parseInt() returns a primitive int. Keep this in mind if such a difference would change the flow of your program.

Let's try this out:

String string = "10";

try {
    intValue = Integer.parseInt(string);
    return true;
} catch (NumberFormatException e) {
    System.out.println("Input String cannot be parsed to Integer.");
}

This results in:

true

Now, we can abstract this functionality into a helper method for convenience:

public static boolean isNumeric(String string) {
    int intValue;
        
    System.out.println(String.format("Parsing string: \"%s\"", string));
        
    if(string == null || string.equals("")) {
        System.out.println("String cannot be parsed, it is null or empty.");
        return false;
    }
    
    try {
        intValue = Integer.parseInt(string);
        return true;
    } catch (NumberFormatException e) {
        System.out.println("Input String cannot be parsed to Integer.");
    }
    return false;
}

Now, we can simply call:

String string = "10";

if(isNumeric(string)) { 
    System.out.println("String is numeric!");
    // Do something
} else {
    System.out.println("String is not numeric.");
}

Running this code would result in:

Parsing string: "10"
String is numeric!

On the other hand, if we expect the String to contain a really big number, then we can call the BigInteger(String) constructor, which translates the String representation into a BigInteger.

Check if String is Numeric with Apache Commons

Apache Commons is one of the most used third-party libraries for expanding the basic Java Framework. It gives us more fine control over core Java classes, in this case, Strings.

We'll be looking at two classes from the Apache Commons library:

  1. NumberUtils
  2. StringUtils

Both of which are very similar to their vanilla Java class counterparts, but with an emphasis on null-safe operations (on numbers and strings respectively), meaning we can even define default values for missing (null) values.

Let's now take a look at how we can check for numeric values using these methods.

NumberUtils.isParsable()

This method accepts a String and checks if it's a parsable number or not, we can be use this method instead of catching an exception when calling one of the methods we mentioned earlier.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This is very good because solutions that involve frequent exception handling should be avoided if possible - this is exactly what this method helps us with.

Note that hexadecimal numbers and scientific notations are not considered parsable.

Now, we don't really even need a convenience helper method, as isParseable() returns a boolean itself:

String string = "10";

if (NumberUtils.isParsable(string)) {
    System.out.println("String is numeric!");
} else {
    System.out.println("String is not numeric.");
}

This code should return:

String is numeric!

NumberUtils.isCreatable()

This method also accepts a String and checks if it's a valid Java number. With this method we can cover even more numbers, because a valid Java number includes even hexadecimal and octal numbers, scientific notation, as well as numbers marked with a type qualifier.

Now, we can even use something along the lines of:

String string = "0x10AB";

if (NumberUtils.isCreatable(string)) {
    System.out.println("String contains a creatable number!");
} else {
    System.out.println("String doesn't contain creatable number.");
}

The output would be:

String contains a creatable number!

NumberUtils.isDigits()

The NumberUtils.isDigits() method checks if a string contains only Unicode digits. If the String contains a leading sign or decimal point the method will return false:

String string = "25";

if (NumberUtils.isDigits(string)) {
    System.out.println("String is numeric!");
} else {
    System.out.println("String isn't numeric.");
}

StringUtils.isNumeric()

The StringUtils.isNumeric() is the StringUtils equivalent of NumberUtils.isDigits().

If the String passes the numeric test, it may still generate a NumberFormatException error when parsed by the methods we mentioned earlier, for example if it is out of range for int or long.

Using this method we can determine if we can parse String into an Integer:

String string = "25";

if (StringUtils.isNumeric(string)) {
    System.out.println("String is numeric!");
} else {
    System.out.println("String isn't numeric.");
}

StringUtils.isNumericSpace()

Additionally, if we expect to find more numbers within a String, we can use isNumericSpace, another useful StringUtilsmethod worth mentioning. It checks if the String contains only Unicode digits or spaces.

Let's check a String that contains numbers and spaces:

String string = "25 50 15";

if (StringUtils.isNumericSpace(string)) {
    System.out.println("String is numeric!");
} else {
    System.out.println("String isn't numeric.");
}

This results in:

String is numeric!

Check if String is Numeric with Regex

Even though most developers will be content with using an already implemented method, sometimes you might have very specific pattern checking:

public static boolean isNumeric(String string) {
    // Checks if the provided string
    // is a numeric by applying a regular
    // expression on it.
    String regex = "[0-9]+[\\.]?[0-9]*";
    return Pattern.matches(regex, string);
}

And then, we can call this method:

System.out.println("123: " + isStringNumeric2("123"));
System.out.println("I'm totally a numeric, trust me: " + isStringNumeric2("I'm totally a numeric, trust me"));

Running this gives us the following output:

123: true
I'm totally a numeric, trust me: false

Conclusion

In this article, we've covered several ways to check if a String is numeric or not (represents a number) in Java.

We've started off using Core Java, and catching a NumberFormatException, after which we've used the Apache Commons library. From there, we've utilized the StringUtils and NumberUtils classes to check whether a String is numeric or not, with various formats.

Last Updated: May 11th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms