簡體   English   中英

將Double轉換為Int數組?

[英]Converting Double into Int Array?

我在一個程序上工作,用戶輸入一個double,然后我把它拆分並放入一個數組(然后我做一些其他的東西)。 問題是,我不知道如何逐個拆分,並把它放入一個int數組。 請幫忙?

繼承人我在尋找:

    double x = 999999.99 //thats the max size of the double
    //I dont know how to code this part
    int[] splitD = {9,9,9,9,9,9}; //the number
    int[] splitDec = {9,9}; //the decimal

您可以將數字轉換為String然后根據分割String . 字符。

例如:

public static void main(String[] args) {
        double x = 999999.99; // thats the max size of the double
        // I dont know how to code this part
        int[] splitD = { 9, 9, 9, 9, 9, 9 }; // the number
        int[] splitDec = { 9, 9 }; // the decimal

        // convert number to String
        String input = x + "";
        // split the number
        String[] split = input.split("\\.");

        String firstPart = split[0];
        char[] charArray1 = firstPart.toCharArray();
        // recreate the array with size equals firstPart length
        splitD = new int[charArray1.length];
        for (int i = 0; i < charArray1.length; i++) {
            // convert char to int
            splitD[i] = Character.getNumericValue(charArray1[i]);
        }

        // the decimal part
        if (split.length > 1) {
            String secondPart = split[1];
            char[] charArray2 = secondPart.toCharArray();
            splitDec = new int[charArray2.length];
            for (int i = 0; i < charArray2.length; i++) {
                // convert char to int
                splitDec[i] = Character.getNumericValue(charArray2[i]);
            }
        }
    }

有幾種方法可以做到這一點。 一種是先獲取double的整數部分並將其賦值給int變量。 然后,您可以使用/%運算符來獲取該int的數字。 (事實上​​,這會產生一個漂亮的功能,所以你可以在下一部分重復使用它。)如果你知道你只處理最多兩個小數位,你可以從double減去整數部分得到分數部分。 然后乘以100得到數字與整數部分。

您可以從double創建一個字符串:

String stringRepresentation  = Double.toString(x);

然后拆分字符串:

String[] parts = stringRepresentation.split("\\.");
String part1 = parts[0]; // 999999
String part2 = parts[1]; // 99

然后使用以下內容將每個轉換為數組:

int[] intArray = new int[part1.length()];

for (int i = 0; i < part1.length(); i++) {
    intArray[i] = Character.digit(part1.charAt(i), 10);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM