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.
Asked
Active
Viewed 442 times
7
-
11Validate the input by parsing with `Integer.parseInt(...)` in a `try/catch(NumberFormatException e)`. – Hovercraft Full Of Eels Jun 19 '12 at 14:20
-
How big your number? Is your number it out range of available types in java (Double/Float) ? – Santosh Jun 19 '12 at 14:21
-
@HovercraftFullOfEels I don't think the OP is talking about `NumberFormatException`. I think is about the `String` when converted to a number(`Integer`), might be out of range. – Kazekage Gaara Jun 19 '12 at 14:22
-
@KazekageGaara Integer.parseInt checks the range – Denys Séguret Jun 19 '12 at 14:22
-
@dystroy if the number is out of range then what happens? Just curious. – Kazekage Gaara Jun 19 '12 at 14:23
-
@KazekageGaara: No the OP was not talking directly about using NumberFormatException, but it is a way to solve his main problem. Please look at *many* of the answers below that show specifically how this is done. – Hovercraft Full Of Eels Jun 19 '12 at 14:29
-
@HovercraftFullOfEels you should answer and be accepted... – Denys Séguret Jun 19 '12 at 14:29
-
@user1423793 : Could you please provide your string that you need to parse as int? – Fahim Parkar Jun 19 '12 at 14:39
-
1Unless you really care about accidental leading or trailing spaces, call String.trim() on the String before calling parseInt() as suggested in all the answers. At least in Java 6, parseInt() throws Exceptions on leading or trailing spaces. – user949300 Jun 19 '12 at 14:43
7 Answers
11
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 */
}

Michael
- 1,239
- 9
- 14
5
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
}

Denys Séguret
- 372,613
- 87
- 782
- 758
3
Parse the string to a BigInteger instead of a regular Integer. This can hold much higher values.
BigInteger theInteger = new BigInteger(stringToBeParsed);

John Snow
- 5,214
- 4
- 37
- 44
-
-
@dystroy. Actually I think it does. The way I read the question is that he wants the user to be able to input any number, but don't want the programm to crash due to the number beeing to large – John Snow Jun 19 '12 at 14:31
-
In fact maybe. Using "int" in the question instead of "integer" would so just be an error. – Denys Séguret Jun 19 '12 at 14:35
0
You could run a check in your code:
- Convert the String into a long.
- Compare the long against the max value for an integer (a constant within the Integer class.)
- If the long is greater than it, you know that it cannot be parsed into an int without overflow.
- If it is less than or equal to it, convert your long into an int.

BlackVegetable
- 12,594
- 8
- 50
- 82
-
-
Because I am silly, clearly. (Wouldn't an int possibly overflow to a negative value, or fail? It would require a try/catch block, which admittedly is the better answer.) – BlackVegetable Jun 19 '12 at 14:25
0
Always parse the string in try catch
block so if any exception or error occurred you know that there is some error in String to int parsing.

Pramod Kumar
- 7,914
- 5
- 28
- 37
0
You could use Apache Commons Lang.
import org.apache.commons.lang.math.NumberUtils;
NumberUtils.toInt( "", 10 ); // returns 10
NumberUtils.toInt( null, 10 ); // returns 10
NumberUtils.toInt( "1", 0 ); // returns 1
The second number is the default if the String is not a numeric value. The first parameter is the String you are trying to convert.
For large numbers I would do the following
BigInteger val = null;
try {
val = new BigInteger( "1" );
} catch ( NumberFormatException e ) {
val = BigInteger.ZERO;
}

mrswadge
- 1,659
- 1
- 20
- 43
0
what about this ?
BigInteger bigInt = BigInteger(numberAsString);
boolean fitsInInt = ( bigInt.compareTo( BigInteger.valueOf(bigInt.intValue()) ) == 0;

Rostislav Matl
- 4,294
- 4
- 29
- 53