I am writing a program that changes doubles into arrays. So if i had this:
double d = 1.23456
I woud want an array like this:
array[0] = 1
array[1] = 2
array[2] = 3
and so on.
Another example:
double d = 3.1415926
to
array[0] = 3
array[1] = 1
array[5] = 9
Some of you wanted to see my code, so here it is:
long l = (new Double(3.1415926)).longValue();
String s = Long.toString(l);
System.out.println(l); //prints 3, so splitting won't have any effect
System.out.println(s); //prints 3, so splitting won't have any effect
Maybe the simplest solution is to create a string from double:
String s = Double.toString(d);
and then parse it skipping decimal dot, and fill your array.
Please Try this
public static void main(String[] args)
{
Double d = 1.2546;
String s = d.toString();
int a[] = new int[s.length()];
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!='.')
{
a[i]=Integer.parseInt(s.charAt(i)+"");
System.out.println(a[i]);
}
}
}
ouput
1
2
5
4
6
double d = 1.23456;
ArrayList<Integer> arrayList = new ArrayList<>();
while (d != 0) {
arrayList.add((int) d);
d = (d - ((int) d)) * 10.0;
}
System.out.println(arrayList.toString());
Probably not the best solution, but it should work.
double d = 3.14159;
String s = String.valueOf(d); // convert the double to a string
s = s.replace(".", ""); // delete all dots from the string
int[] ints = new int[s.length()]; // create an array to hold each digit
for (int i = 0; i < ints.length; i++) { // foreach character in the string
// convert the next character in the string to an int and save it to array
ints[i] = Integer.parseInt(s.substring(i, i + 1));
}
// print the array
for (int i : ints) System.out.println(i);
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.