[Q#5290588][A#5290628] How can I extract the first 4 digits from an int? (Java)
https://stackoverflow.com/q/5290588
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.
Answer
https://stackoverflow.com/a/5290628
Try following: Wherever you want integer for first four character use intForFirst4Char and where you wanna use string use appropriate. Hope this helps.
APIzation
String str = "1234567890";
int fullInt = Integer.parseInt(str);
String first4char = str.substring(0,4);
int intForFirst4Char = Integer.parseInt(first4char);
package com.stackoverflow.api;
public class Human5290628 {
public static int extractFirstFourIntsFromString(String str) {
int fullInt = Integer.parseInt(str);
String first4char = str.substring(0, 4);
return Integer.parseInt(first4char);
}
}
package com.stackoverflow.api;
/**
* How can I extract the first 4 digits from an int? (Java)
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/5290628">https://stackoverflow.com/a/5290628</a>
*/
public class APIzator5290628 {
public static int extractDigit(String str) throws Exception {
int fullInt = Integer.parseInt(str);
String first4char = str.substring(0, 4);
return Integer.parseInt(first4char);
}
}