I want to check is a String
I pass to Integer.valueOf(String s)
a valid String to parse. If one is not parsable I need to return 0.
I do it in the following way:
try{
Integer.valueOf(String s)
} catch(NumberFormatException e) {
return 0;
}
Is it a bad way to do that?
method 1: use a regular expression to check for validity of being a number
public static int parseStrToInt(String str) {
if (str.matches("\\d+")) {
return Integer.parseInt(str);
} else {
return 0;
}
}
method 2: use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric
public static int strToInt(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
if (str.length() == pos.getIndex()) {
return Integer.parseInt(str);
} else {
return 0;
}
}
I would have used:
s = s.trim(); // sometimes user inputs white spaces without knowing it
int value;
if (s.length() == 0) {
value = 0; // obviously not a string
} else {
try{
value = Integer.valueOf(s);
} catch(NumberFormatException e) {
value = 0;
}
}
// do whatever you like here
Hi this will do even the number is double or long, which is useful always while parsing.
List<String> myStrings = new ArrayList<String>();
myStrings.add("text");
myStrings.add("25");
myStrings.add("102.23333333");
myStrings.add("22.34");
NumberFormat nf = NumberFormat.getInstance();
for( String text : myStrings){
try {
System.out.println( nf.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With