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.
To check if the string contains numbers only, in the try block, we use Double‘s parseDouble() method to convert the string to a Double.
If it throws an error (i.e. NumberFormatException error), it means the string isn’t a number and numeric is set to false. Else, it’s a number.
However, if you want to check if for a number of strings, you would need to change it to a function. And, the logic is based on throwing exceptions, this can be pretty expensive.
Leave a Reply