Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make sure a String can be stored as an int in java

I am making a web-based application and i have text-fields where the values are stored as Strings. The problem is that some of the text-fields are to be parsed into ints and you can store much bigger numbers in Strings than you can in an int. My question is, what is the best way to make sure that the String number can be parsed into an int without erroring out.

like image 957
user1423793 Avatar asked Jun 19 '12 14:06

user1423793


2 Answers

You can use a try/catch structure for that.

try {
    Integer.parseInt(yourString);
    //new BigInteger(yourString);
    //Use the above if parsing amounts beyond the range of an Integer.
} catch (NumberFormatException e) {
    /* Fix the problem */
}
like image 197
Michael Avatar answered Sep 30 '22 08:09

Michael


The Integer.parseInt method checks the range as is explicited by the javadoc :

An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
The value represented by the string is not a value of type int.
Examples:
 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787

So the correct way is to try parsing the string :

try {
    Integer.parseInt(str);
} catch (NumberFormatException e) {
    // not an int
}
like image 41
Denys Séguret Avatar answered Sep 30 '22 08:09

Denys Séguret