简体   繁体   中英

If a String containing a number bigger than Integer.MAX_VALUE

我想找到给定的字符串“99999999999999999999999999”或任何不适合任何数据类型的大量数字。我想查找该数字是否大于Integer.MAX_VALUE

Use BigInteger

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

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

您可以从字符串构造一个BigInteger对象,然后将该BigIntegerInteger.MAX_VALUE进行比较。

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM