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

I am looking for a way to convert a string to int, then extract and return the first 4 digits in this int.

Note. It must remain as a string so that other methods work correctly.

+4
source share
4 answers

Try the following:

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

Wherever you want the integer for the first four characters to use intForFirst4Char and where you want to use a string, use the appropriate one.

Hope this helps.

+5
source

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; } } 

}

0
source

This will give you the numbers 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; } 

Call method

 digitArrayLR = convertNumbertoArrayLtoR(digitArrayLR, numberInput, maxDivisor, 0); 
0
source

Source: https://habr.com/ru/post/1343543/


All Articles