Ian Fako
Ian Fako

Reputation: 1210

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?

Upvotes: 28

Views: 9626

Answers (6)

Timetrax
Timetrax

Reputation: 1493

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

Upvotes: -2

Aaron
Aaron

Reputation: 24802

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.

Upvotes: 13

Rahim Dastar
Rahim Dastar

Reputation: 1269

I don't know straight way but I think it is simpler:

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

Upvotes: 23

The Scientific Method
The Scientific Method

Reputation: 2436

this would work also

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

Upvotes: 0

Eugene
Eugene

Reputation: 120848

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();

Upvotes: 4

Sveteek
Sveteek

Reputation: 161

You can use in java 8

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

Upvotes: 3

Related Questions