简体   繁体   English

如何从int中提取前4位数? (JAVA)

[英]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. 我正在寻找一种方法将字符串转换为int,然后提取并返回此int中的前4位数字。

Note: It must remain as a String for the other methods to work properly, though. 注意:它必须保留为String,以便其他方法正常工作。

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. 无论你想要的前四个字符的整数使用intForFirst4Char ,你想在哪里使用适当的字符串使用。

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 { 公共类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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从java中的句子中提取数字? - How to extract digits from a sentence in java? 如何从字符串 java 中提取未知数字 - How to Extract unknown digits from String java 如何使用正则表达式 java 从字符串中提取第一个字母和以下三个数字 - How to extract the first letter and the following three digits from a string using regex java 如何从EditText获取前10位数字,并在TextView中设置这些数字? - How can I get the first 10 digits from EditText, and set this digits in a TextView? 如何以编程方式从Java中的FLV文件中提取预览图像(如第一帧)? - How can I programmatically extract a preview image - like the first frame - from an FLV file in Java? 从Java中的字符串中提取数字 - Extract digits from a string in Java 如何使用for循环交换Java中数字的第一个和最后一个数字? - How can I swap the first and last digits of a number in Java using for for-loops? 如何从字符串中提取数字? - How to Extract digits from string? 如何为数字的数字数组(int)分配内存,其长度等于该数字的位数? - How can I allocate memory for an array of digits (int) of a number with the length being equal to the number of digits of that number? 如何基于第一位数字java从数组中获取整数值 - How to get integer values from array based on first digits java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM