Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the first 4 digits from an int? (Java)

Tags:

java

I'm looking to find a way to convert a string to an int in order to then extract and return the first 4 digits in this int.

Note: It must remain as a String for the other methods to work properly, though.

like image 814
Jimmy Avatar asked Mar 13 '11 16:03

Jimmy


2 Answers

Try following:

String str = "1234567890";
int fullInt = Integer.parseInt(str);
String first4char = str.substring(0,4);
int intForFirst4Char = Integer.parseInt(first4char);

Wherever you want integer for first four character use intForFirst4Char and where you wanna use string use appropriate.

Hope this helps.

like image 84
Harry Joy Avatar answered Nov 09 '22 15:11

Harry Joy


Integer.parseInt(myIntegerString.substring(0, 4))

Also, read the JDK:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

like image 20
Travis Webb Avatar answered Nov 09 '22 13:11

Travis Webb