Convert double to int array Convert double to int array arrays arrays

Convert double to int array


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