Im working on a program, where the user inputs a double, and I split the double up and put it into an array(Then I do some other stuff).
The problem is, im not sure how to split up the double by digit, and put it into an int array. Please help?
Heres what im looking for:
double x = 999999.99 //thats the max size of the double
//I dont know how to code this part
int[] splitD = {9,9,9,9,9,9}; //the number
int[] splitDec = {9,9}; //the decimal
You can convert the number to String
then split the String based on .
character.
For example:
public static void main(String[] args) {
double x = 999999.99; // thats the max size of the double
// I dont know how to code this part
int[] splitD = { 9, 9, 9, 9, 9, 9 }; // the number
int[] splitDec = { 9, 9 }; // the decimal
// convert number to String
String input = x + "";
// split the number
String[] split = input.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++) {
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
}
// the decimal part
if (split.length > 1) {
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++) {
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
}
There are several ways to do this. One is to first get the whole number part of the double
and assign it to an int
variable. Then you can use the /
and %
operators to get the digits of that int
. (In fact, this would make a nifty function so you can reuse it for the next part.) If you know that you are only dealing with up to two decimal places, you can subtract the whole number part from the double to get the fractional part. Then multiply by 100 and get the digits as with the whole number part.
You could create a string from the double:
String stringRepresentation = Double.toString(x);
Then split the string:
String[] parts = stringRepresentation.split("\\.");
String part1 = parts[0]; // 999999
String part2 = parts[1]; // 99
Then convert each of these to your arrays using something like:
int[] intArray = new int[part1.length()];
for (int i = 0; i < part1.length(); i++) {
intArray[i] = Character.digit(part1.charAt(i), 10);
}