如何将Sting`8.1.009.125`转换为`double`数组?爪哇

时间:2019-01-16 18:15:34

标签: java arrays string

如何将Sting 8.1.009.125转换为double数组?

double[] arr = new double[4];
arr[0] = 8;
arr[1] = 1;
arr[2] = 0.09;
arr[3] = 125;

不考虑。字符串的长度可以无限制,并且开头可能包含零。

  for (int i = 0; i <arr.length ; i++) {
        arr[i] = Double.valueOf(s1.replace(".", ""));
    }

填充错误的结果:[8.1009125E7, 8.1009125E7, 8.1009125E7, 8.1009125E7]

我需要从[8, 1, 0.09, 125]获得String = "8.1.009.125"

主要问题是字符串由点分隔。

我需要保存String temp = "8.1.009.125"中的值0.09

获取一个Number数组(浮点数,双精度)[8, 1, 0.09, 125]

我该怎么做?

可能还有另一种方法吗?除了数组?

3 个答案:

答案 0 :(得分:3)

那当然是未经测试的代码...

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;
    }
}

答案 1 :(得分:2)

针对您的具体情况,有一些解决方法。 如果您在A = LOAD 'input.txt' AS (id: int, data:bag{(score:float, flag:boolean)}); B = FOREACH A { filtered_data = FILTER data by flag == true; GENERATE id, filtered_data; } store B into '$output'; 开头的字符串为零,则可以使用正确的格式009创建一个新字符串,然后将其转换为0.09的双精度值

尝试一下:

Double.valueOf(string)

答案 2 :(得分:0)

首先split String,创建一个具有相同大小的double数组,然后复制元素,并在必要时进行修改。

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]);
}