Wednesday, 4 May 2011

Way to check if a java string is a number

We have seen here how to convert java string to number. So this is one way of checking whether the given string is number or not. We can simply write:

int age = new Integer(ageString).intValue();  



But there is a possibility that the user might have entered an invalid number. Probably they entered “thirty” as their age.
If you try to convert “thirty” to a number you will get NumberFormatException. One way to avoid this is to catch and handle the NumberFormatException. But this is not the ideal and the most elegant solution to convert a string to a number in Java.

Another approach is to validate the input string before performing the conversion using Java regular expression. I like that second approach because it is more elegant and it will keep your code clean.

So here is a function which will take a String and check whether its number or not using regular expression:

public static boolean isStringANumber(String number){  
boolean isValid = false;
/*Explaination:
[-+]?: Can have an optional - or + sign at the beginning.
[0-9]*: Can have any numbers of digits between 0 and 9
\\.? : the digits may have an optional decimal point.
[0-9]+$: The string must have a digit at the end.
If you want to consider x. as a valid number change
the expression as follows. (but I treat this as an invalid number.).
String expression = "[-+]?[0-9]*\\.?[0-9\\.]+$";
*/
String expression = "[-+]?[0-9]*\\.?[0-9]+$";
CharSequence inputStr = number;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}

No comments:

Post a Comment