简体   繁体   中英

How can I extract the first 4 digits from an int? (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.

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.

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))

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM