Reputation: 85
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.
Upvotes: 7
Views: 32280
Reputation: 15018
Integer.parseInt(myIntegerString.substring(0, 4))
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
Upvotes: 10
Reputation: 21
You can either use the following:
Integer.parseInt("123".substring(0, 2))
OR
int temp = 12345678;
int result = temp / (int)Math.pow(10, (int)(Math.log10(temp) - 1))
Upvotes: 2
Reputation: 481
This will give you digits in an array
public Integer[] convertNumbertoArrayLtoR(Integer[] array, Integer number, Integer maxDivisor, Integer i)
{
if (maxDivisor > 0)
{
Integer digit = number/maxDivisor;
array[i] = digit;
number = number%maxDivisor;
maxDivisor = (int) Math.floor(maxDivisor/10);
i++;
convertNumbertoArrayLtoR(array, number, maxDivisor, i);
}
return array;
}
Calling method
digitArrayLR = convertNumbertoArrayLtoR(digitArrayLR, numberInput, maxDivisor, 0);
Upvotes: 0
Reputation: 1
public class ExtractingDigits {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num = 1542,ans=0;
for(int i=1; i<=4; i++){
ans=num%10;
System.out.println(ans);
num = num/10;
}
}
}
Upvotes: 0
Reputation: 59660
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.
Upvotes: 9