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?
round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.
An array is a sequence of values; the values in the array are called elements. You can make an array of int s, double s, or any other type, but all the values in an array must have the same type.
You can have an array of Object s, in which case you can put Integer and Double objects in it.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With