There may be a scenario, if we want to determine whether a string is completely numeric or not, such as we want a user to input a number and our program should multiply it by 5 and return the result. User is a human. He may mistakenly input an alphanumeric string by mistake or to check the correctness of our program.
Off course, we would not like to show an exception trace to the user instead of the result. Better we check the input for its validity before processing. Below are various ways using which we may check that an input String is completely a number or not.
Check out:
Way 1: Using parseInt method of Integer class
public static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
Detail: If the string is not numeric (entirely), then it will throw an error while parsing and we will return false from catch block.
Way 2: Using regular expression
public static boolean isNumeric(String string) {
return string.matches("^[-+]?\\d+(\\.\\d+)?$");
}
Detail: This regular expression will take care of negative, positive and decimal numbers as well.
Way 3: Using a character array
public static boolean isNumericArray(String str) {
char[] digits = str.toCharArray();
if (digits.length <= 0) {
return false;
}
int index = 0;
//check if there is a minus sign
if (digits[0] == '-' && digits.length > 1) {
index = 1;
}
for (; index < digits.length; index++) {
//check each character to be a number
if (!Character.isDigit(digits[index])) {
return false;
}
return true;
}
Detail: Convert the string to a character array and then iterate over this array. Simply use isDigit
method of java.lang.Character
class to check if the character is a number or not. As soon as a non-numeric digit is encountered we return a Boolean
result to indicate that the string is non-numeric.
Way 4: Using NumberFormat
and ParsePosition
classes of java api
public static boolean isNumericStr(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
Detail: Create a NumberFormat
(from java.text
package) instance and use it to parse the given string. Assign a ParsePosition
(again from java.text
package) object while parsing. The ParsePosition
increments its index with every character parsed and stops as soon as it is unable to parse a character into a number.
Utilizing this property of ParsePosition
we check that its index is equal to the string. If both values are same means that the parser was able to parse the complete string (without any error) which implies that the string is numeric.
If there are any other ways which you are familiar with, do let us know by your valuable comments.
Note: Reversing the result from code snippets in the above examples, we can also utilize it to check whether a String contains a number or not.