首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否将Double转换为Int数组?

是否将Double转换为Int数组?
EN

Stack Overflow用户
提问于 2013-03-12 08:29:32
回答 3查看 1.5K关注 0票数 0

我正在开发一个程序,用户输入一个双精度数,然后我将双精度数分成一个数组(然后我做一些其他的事情)。问题是,我不确定如何按数字拆分双精度数,并将其放入整型数组中。请帮帮忙?

这就是我要找的:

代码语言:javascript
复制
    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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-03-12 08:40:07

您可以将数字转换为String,然后根据.字符拆分字符串。

例如:

代码语言:javascript
复制
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]);
            }
        }
    }
票数 2
EN

Stack Overflow用户

发布于 2013-03-12 08:34:24

有几种方法可以做到这一点。一种方法是首先获取double的整数部分,并将其赋给一个int变量。然后,您可以使用/%运算符来获取该int的位数。(实际上,这将是一个很好的函数,这样您就可以在下一部分中重用它。)如果您知道最多只能处理两位小数,则可以从双精度数中减去整数部分,得到小数部分。然后乘以100,得到与整数部分相同的数字。

票数 0
EN

Stack Overflow用户

发布于 2013-03-12 08:39:57

你可以从double中创建一个字符串:

代码语言:javascript
复制
String stringRepresentation  = Double.toString(x);

然后拆分字符串:

代码语言:javascript
复制
String[] parts = stringRepresentation.split("\\.");
String part1 = parts[0]; // 999999
String part2 = parts[1]; // 99

然后使用如下命令将它们转换为您的数组:

代码语言:javascript
复制
int[] intArray = new int[part1.length()];

for (int i = 0; i < part1.length(); i++) {
    intArray[i] = Character.digit(part1.charAt(i), 10);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15351162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档