How would you check if a String was a number before parsing it?
Dec 28, 2020 in Java 116 views

## 3 answers to this question.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.is parsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

• 65,870 points

Perhaps the easiest and the most reliable way to check whether a String is numeric or not is by parsing it using Java's built-in methods:

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

If these methods don't throw any NumberFormatException, then it means that the parsing was successful and the String is numeric:

```public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}```
answered Dec 28, 2020 by Nikita

Check if a string is numeric

```public class Numeric {

public static void main(String[] args) {

String string = "12345.15";
boolean numeric = true;

try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}

if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}```

Output

`12345.15 is a number`

In the above program, we have a String named string that contains the string to be checked. We also have a boolean value numeric which stores if the final result is numeric or not.

answered Dec 28, 2020 by Carlos

## What's the best way to check if a String represents an integer in Java?

You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE

## How do I check if a string contains a substring in Java?

Hi@akhtar, The first and foremost way to check ...READ MORE

## How can I convert a String variable to a primitive int in Java

Here are two ways illustrating this: Integer x ...READ MORE

## How to reverse a string in java?

public static String reverse(String s) { ...READ MORE

## Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

## One line initialization of an ArrayList object in Java

In Java 8 or earlier: List<String> string = ...READ MORE

## Generate an alpha-numeric string randomly

Java supplies a way of doing this ...READ MORE

## How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

+1 vote