PetrolHead007
PetrolHead007

Reputation: 105

If a String containing a number bigger than Integer.MAX_VALUE

I want to find if given String "99999999999999999999999999" or any massive number which would not fit in any datatype.I would like to find if that number is bigger than Integer.MAX_VALUE

Upvotes: 5

Views: 9185

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can parse it as an int and catch an exception or BigInteger, or you can do a String comparison.

static final String MAX_INT_STR = Integer.toString(Integer.MAX_VALUE);

public static boolean checkInt(String s) {
    return s.length() > MAX_INT_STR.length() || s.compareTo(MAX_INT_STR) > 0;
}

This could be used to avoid throwing some Exceptions before trying to parse it.

NOTE: This doesn't check that it only contains digits, but if it's a positive number it will check it is in bounds without parsing the string.

Upvotes: 2

Mark
Mark

Reputation: 5239

Try the following code to check if it's too big to fit inside an integer:

String num = "99999999999999999999999999";

try {
    Integer.parseInt(num);
} catch(NumberFormatException ex) {
    System.out.println("String did not fit in integer datatype");
}

This code will attempt to parse num into an integer, we can catch whenever that goes wrong and execute code when that happens (in this case a simple println).

From parseInt():

Throws: NumberFormatException - if the string does not contain a parsable integer.

Upvotes: -1

Eran
Eran

Reputation: 393801

You can call parseInt and catch NumberFormatException, which will be thrown if the number is too large (though it will also be thrown if the String has non-numeric characters).

If you want to avoid the exception, you can run the following checks:

  • If the String has more than 10 characters (or 11 if the first character is '-' or '+'), it must be larger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE.
  • Otherwise, call Long.parseLong() and compare the result to Integer.MAX_VALUE.

Upvotes: 6

Michael
Michael

Reputation: 44150

Use BigInteger

BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
BigInteger value = new BigInteger("whatever");

if (value.compareTo(maxInt) > 0)
{
    // larger
}

Upvotes: 16

NPE
NPE

Reputation: 500317

You could construct a BigInteger object from the string and then compare that BigInteger to Integer.MAX_VALUE.

Upvotes: 5

Related Questions