简体   繁体   中英

How can I convert a above 16 digit string to integer in java?

i Am beginner of java. pls help me,

int i = Integer.parseInt("9876543210123456");
System.out.println("Integer: " + i);

i got below error,

java.lang.NumberFormatException for input string : "9876543210123456"

超出整数限制,您需要BigInteger

BigInteger b = new BigInteger("9876543210123456");

You can't convert the above value to an int , as it exceeds Integer's max value: 2,147,483,647.

Instead try:

Long.parseLong("9876543210123456");

Long has a maximum value of 9,223,372,036,854,775,807.

To check the maximum values of these and other primitive data types try:

Integer.MAX_VALUE;
Long.MAX_VALUE;
// etc for Float, Double...
// Also try MIN_VALUE

In Java, the primitive int data type is a 32-bit signed two's complement integer http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

You can use Long:

long i = Long.parseLong("9876543210123456");
System.out.println("Long: " + i);

Refer to the API here - http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html

Or you can also use BigInteger:

BigInteger i = new BigInteger("9876543210123456");
System.out.println("BigInteger: " + i);

Refer to the API here - http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

BigInteger is analogous to the primitive integer types except that it provides arbitrary precision, hence operations on BigIntegers do not overflow or lose precision. In addition to standard arithmetic operations, BigInteger provides modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

If you are confused whether to use a primitive or an object reference, here is a good discussion

When to use primitive and when reference types in Java

In java range of int is from -2,147,483,648 to 2,147,483,647. So try long instead of int.

NumberFormat nf = NumberFormat.getInstance();

You can also use a NumberFormat to parse numbers:

 myNumber = nf.parse("9876543210123456");

see below

http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html

Although BigInteger might work, but the best way is to keep it String only and display it as String . That's the ideal way for dealing with long digit numbers and you won't end up with any type of exceptions.

long x = Long.parseLong("9876543210123456");

System.out.println("Integer: " + x);

or else ple use follow line

BigInteger bint = new BigInteger("9999999999999999", 16);

Please try this..Can't avle to convert the more than 13 digits string to int..so,you should convert to long

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