Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer.parseInt failed to parse a string

Tags:

java

I'm parsing a string of 15 digits like this:

String str = "100004159312045";
int i = Integer.parseInt(str);

I'm getting an exception when doing so. Why? What are the limitations for Integer.parseInt? What other options do I have for converting such long string to a number?

like image 418
Alon Avatar asked Nov 06 '11 21:11

Alon


2 Answers

Your number is too large to fit in an int which is 32 bits and only has a range of -2,147,483,648 to 2,147,483,647.

Try Long.parseLong instead. A long has 64 bits and has a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

like image 80
Mark Byers Avatar answered Oct 07 '22 12:10

Mark Byers


because int's maximum value is a little above 2,000,000,000

you can use long or BigInteger

long has double the digits it can store (the max value is square that of int) and BigInteger can handle arbitrarily large numbers

like image 26
ratchet freak Avatar answered Oct 07 '22 13:10

ratchet freak