简体   繁体   English

将double转换为int数组

[英]Convert double to int array

I have a double 我有一个双

double pi = 3.1415;

I want to convert this to a int array 我想将其转换为int数组

int[] piArray = {3,1,4,1,5};

I came up with this 我想出了这个

double pi = 3.1415;
String piString = Double.toString(pi).replace(".", "");
int[] piArray = new int[piString.length()];
for (int i = 0; i <= piString.length()-1; i++)
   piArray[i] = piString.charAt(i) - '0'; 

It's working but I don't like this solution because I think a lot of conversions between datatypes can lead to errors. 它工作但我不喜欢这个解决方案,因为我认为数据类型之间的大量转换可能会导致错误。 Is my code even complete or do I need to check for something else? 我的代码是否完整或是否需要检查其他内容?

And how would you approach this problem? 那你怎么解决这个问题呢?

I don't know straight way but I think it is simpler: 我不知道直道,但我觉得它更简单:

int[] piArray = String.valueOf(pi)
                      .replaceAll("\\D", "")
                      .chars()
                      .map(Character::getNumericValue)
                      .toArray();

Since you want to avoid casts, here's the arithmetic way, supposing you only have to deal with positive numbers : 既然你想避免强制转换,这里是算术方式,假设你只需要处理正数:

List<Integer> piList = new ArrayList<>();
double current = pi;
while (current > 0) {
    int mostSignificantDigit = (int) current;
    piList.add(mostSignificantDigit);
    current = (current - mostSignificantDigit) * 10;
}

Handling negative numbers could be easily done by checking the sign at first then using the same code with current = Math.abs(pi) . 通过首先检查符号然后使用current = Math.abs(pi)使用相同的代码,可以轻松地处理负数。

Note that due to floating point arithmetics it will give you results you might not expect for values that can't be perfectly represented in binary. 请注意,由于浮点算术,它将为您提供无法用二进制表示的值的结果。

Here 's an ideone which illustrates the problem and where you can try my code. 是一个说明问题以及在哪里可以尝试我的代码的想法。

int[] result = Stream.of(pi)
            .map(String::valueOf)
            .flatMap(x -> Arrays.stream(x.split("\\.|")))
            .filter(x -> !x.isEmpty())
            .mapToInt(Integer::valueOf)
            .toArray();

Or a safer approach with java-9 : 或者使用java-9更安全的方法:

 int[] result = new Scanner(String.valueOf(pi))
            .findAll(Pattern.compile("\\d"))
            .map(MatchResult::group)
            .mapToInt(Integer::valueOf)
            .toArray();

你可以在java 8中使用

int[] piArray = piString.chars().map(Character::getNumericValue).toArray();

这也行

int[] piArray = piString.chars().map(c -> c-'0').toArray();

This solution makes no assumptions and uses string manipulation to get you the result you want. 此解决方案不做任何假设,并使用字符串操作来获得您想要的结果。 Gets the double, turns it to a string, removes illegal characters, then casts each of the remaining characters into ints and stores them in the array - in the order they appear in the double 获取double,将其转换为字符串,删除非法字符,然后将每个剩余字符转换为整数并将它们存储在数组中 - 按照它们出现在double中的顺序

        double pi           = 3.1415;
        String temp         = ""+ pi;
        String str          = "";
        String validChars   = "0123456789";

        //this removes all non digit characters 
        //so '.' and '+' and '-' same as string replace(this withThat)
        for(int i =0; i<temp.length(); i++){
          if(validChars.indexOf(temp.charAt(i)) > -1 ){
              str = str +temp.charAt(i);
          }
        }

        int[] result = new int[str.length()];

        for(int i =0; i<str.length(); i++){
          result[i] = Integer.parseInt(""+str.charAt(i));
          System.out.print(result[i]);
        }

        return result; //your array of ints

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

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