Posted by Marta on December 18, 2020 Viewed 2724 times

In this article, we will examine **how to check if a String is a number in Java.** There are several ways to achieve this in Java. We will discuss each of them, see how they work, and analyze their performance. As a result, you will choose the one that better adjusts to your use case.

There are many occasions when your code will receive a string and check if a String is a number and, if so, **convert it to a number to perform a mathematical operation**. For example, imagine your application asks the user to enter his/her age, and you need to check is above 18. To do this simple check, you will first need to check if the string is a number; if so, convert it, and then check if it is above 18.

Let’s explore each way of checking if a String is a Number!

When checking if a String is a number, it is essential to clarify what we will consider. For instance, if the String contains white spaces, should we consider it a number? What about white spaces between the digits? Do we want to accept negative numbers with a leading hyphen?

Additionally, you need to think about floating numbers. Should we only accept a dot to separate the decimal part? The answer to those questions will determine the method to use.

Apache offers a library

, which provides the functionality to check if a string is numeric and a lot more capabilities for String manipulation, basic numerical methods, concurrency, etc.**commons-lang3**

In case you are using **maven,** this is the **dependency **you will need to add yo your project:

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

We will use two classes that contain the specific functionality we are after, which are ** StringUtils and NumberUtils**. See how you can use them to check if a String is a number:

public static boolean checkNumberWithApache1(String text){ return StringUtils.isNumeric(text); }

Now, let’s execute this function against different numbers, and see the results we get, to understand better how ** StringUtils.isNumeric() **works:

Is a number '1234'? true Is a number ' 1234'? true Is a number '12 34'? false Is a number '-1234'? false Is a number '+1234'? false Is a number '1.234'? false Is a number '12'34'? false Is a number '12,34'? false

As you can see the `StringUtils.isNumeric()`

won’t accept positive or negative signs. And it won’t accept decimal as numbers.

You can also use the method

to check if a String is a number, also included in the apache commons library. See below how to use the function:**NumberUtils.isParsable()**

public static boolean checkNumberWithApache2(String text){ return NumberUtils.isParsable(text); }

And here are the outputs that the above function will return:

Is a number '1234' ? true Is a number ' 1234'? true Is a number '12 34'? false Is a number '-1234'? true Is a number '+1234'? false Is a number '1.234'? true Is a number '12'34'? false Is a number '12,34'? false

`NumberUtils.isParsable()`

will behave as `StringUtils.isNumeric()`

. However, it will also include negative numbers and decimal numbers that use a dot to separate the decimal part.

You can also check if a string is numeric using Java. **Combining the parseFloat along with exception handling**, you can quickly implement this functionality. This way to avoid using a third-party library; however, this method is less efficient compared to previous ones.

public static boolean checkNumberWithJava(String text){ try { Float.parseFloat(text); return true; } catch(NumberFormatException ex){ return false; } }

And here are the outputs you will obtain:

Is a number '1234'? true Is a number ' 1234'? true Is a number '12 34'? false Is a number '-1234'? true Is a number '+1234'? true Is a number '1.234'? true Is a number '12'34'? false Is a number '12,34'? false

And of course, you can also check if a string is numeric using java8. The method below will **go through every digit and check if it is a number**. If there is any digit that is not a number, the method will return false.

public static boolean checkNumberWithJava8(String text){ return text.chars().allMatch(Character::isDigit); }

And here are the outputs of this method:

Is a number '1234'? true Is a number ' 1234'? false Is a number '12 34'? false Is a number '-1234'? false Is a number '+1234'? false Is a number '1.234'? false Is a number '12'34'? false Is a number '12,34'? false

Another possible way is by using regular expressions. This method gives flexibility since it allows you to **define what should be considered a number through a regular expression**. Although less efficient than the apache methods, this method will enable you to determine what character is allowed in a number. For instance, in this case, the negative sign and dots are accepted.

public static boolean checkNumberWithRegex(String text){ return text.matches("-?\\d+(\\.\\d+)?"); }

Let’s see the outputs:

Is a number '1234'? true Is a number ' 1234'? false Is a number '12 34'? false Is a number '-1234'? true Is a number '+1234'? false Is a number '1.234'? true Is a number '12'34'? false Is a number '12,34'? false

And lastly, using the

is another provided by Java that will allow you to check if a string is a number. The **NumberFormat**

method would parse the string and return a Number if the string was numeric. Otherwise, It will throw an exception.**parse()**

public static boolean checkNumberWithNumberFormat(String text){ try{ NumberFormat.getInstance().parse(text); return true; }catch(ParseException e){ return false; } }

And here are the outputs for different strings:

Is a number '1234'? true Is a number ' 1234'? false Is a number '12 34'? true Is a number '-1234'? true Is a number '+1234'? false Is a number '1.234'? true Is a number '12'34'? true Is a number '12,34'? true

After seeing these methods, Which one is the best to use? **One way to compare different implementations is to measure time performance and pick the fastest one**. Below you can see the code snippet I use to measure one of the functions’ time performance.

This code snippet will create one million strings contains each a number and then measure how much time will take to check if all those strings are numeric.

List<String> numbers = new Random().ints(1000000).boxed().map(num-> String.valueOf(num)).collect(Collectors.toList()); long startTime = System.currentTimeMillis(); numbers.forEach( numInText ->{ checkNumberWithApache1(numInText); }); long duration = System.currentTimeMillis()-startTime; System.out.println("Running the number check took: " + duration + " ms");

These are the results after running the code snipper for each of the functions created previously.

Running the number check took(using Apache StringUtils ): 54 ms Running the number check took(using Apache NumberUtils): 62 ms Running the number check took(using Java): 1040 ms Running the number check took(using Java8): 223 ms Running the number check took(using Regex): 683 ms Running the number check took(using NumberFormat): 1323 ms

As we can see, the apache commons methods are considerably faster, followed by the Java8 implementation.

In conclusion, we have seen five different how to check if a string is a number: apache-commons, regex, Java, java8, and Java numberformat. My advice is to pick the implementation that best fits your use case, so you don’t need to write too much extra code. However, keep in mind the apache commons methods are the fastest!

I hope you enjoy this article, and thank you so much for reading and supporting this blog!

Happy Coding!

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

Unique lay-out and teaching programming style helping new concepts stick in your memory

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Excellent read for anyone who already know how to program and want to learn Best Practices

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java