Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check is passed string parsable to Integer?

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?

like image 691
St.Antario Avatar asked Sep 29 '14 11:09

St.Antario


3 Answers

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;
    }
}
like image 138
Vipul Paralikar Avatar answered Oct 26 '22 21:10

Vipul Paralikar


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
like image 21
yaser eftekhari Avatar answered Oct 26 '22 21:10

yaser eftekhari


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();
    }
}
like image 39
srinivasan Elangovan Avatar answered Oct 26 '22 20:10

srinivasan Elangovan