How to convert Sting 8.1.009.125
to double
array?
double[] arr = new double[4];
arr[0] = 8;
arr[1] = 1;
arr[2] = 0.09;
arr[3] = 125;
Not considered.String may be ulimited length, and may contains zeros at the begining.
for (int i = 0; i <arr.length ; i++) {
arr[i] = Double.valueOf(s1.replace(".", ""));
}
result for arr filling: [8.1009125E7, 8.1009125E7, 8.1009125E7, 8.1009125E7]
I need to get [8, 1, 0.09, 125]
from String = "8.1.009.125"
Main problem is String delimeted by dots.
And I need save value 0.09 from String temp = "8.1.009.125"
to get an Number array (float, double) [8, 1, 0.09, 125]
How can I do this?
May be there is another way? Besides array?
That's of course untested code...
public Double[] convertTab(String myStr) {
//We start by splitting the string:
String[] tab = myStr.split("\\.");
//We need a structure of double as a result
List<Double> result = new ArrayList<Double>();
//Then we loop on the different elements of the table
for (String sNum : tab) {
//Then we convert, which isn't easy because the rules are ambiguous in your question
result.add(convertDouble(sNum);
}
return result.toArray();
}
public double convertDouble(String sDouble) {
int accu = 1;
for (int i=0;i<sDouble.length();i++) {
//We count the number of 0
if (sDouble.charAt(i) == '0') {
accu = accu*10;
} else {
//Parsing of the remaining digits and division
return Double.parseDouble(sDouble)/accu;
}
}
There is some workaround for your specific case. If you have string with zero at the begining 009
you can create a new one with right format 0.09
and then convert to double value as Double.valueOf(string)
Try this:
public static void main(String[] args) {
String s = "8.1.009.125";
String[] strings = s.split("\\.");
for (String string : strings) {
if (string.startsWith("0")) {
string = "0." + string.substring(1);
}
System.out.println(Double.valueOf(string));
}
}
First you split
your String
, create a double
array with the same size and copy the elements, modifying them where necessary.:
String inputArray[] = input.split("\\.");
double outputArray = new double[input.length];
for (int index = 0; index < inputArray.length; index++) {
if ((inputArray[index].length() > 1) && (inputArray[index].startsWith("0"))) inputArray = inputArray.substring(0, 1) + "." + inputArray.substring(1);
outputArray[index] = Double.valueOf(inputArray[index]);
}
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.