繁体   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