简体   繁体   中英

Convert double to int array

I have a double

double pi = 3.1415;

I want to convert this to a int array

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) .

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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