从Java中的字母数字字符串中提取double值

时间:2012-07-24 09:42:18

标签: java android

我正在寻找能够完成标题所说的功能。

我最终编写的代码解析了每个字符,并创建了另一个字符串 Double.parseDouble 。其中提出StringIndexoutOfBounds例外。这显然不是可行的方法。

  

代码块在这里

int i = 0;
char c = q.charAt(i);
if (Character.isDigit(c)) {
    try {
        String h = "" + c;
        while (Character.isDigit(c) || c == '.') {
            if (i == (q.length() - 1)) if (Character.isDigit(q.charAt(i + 1)) || (q.charAt(i + 1) == '.')) {
                Log.i("CalcApps", "within while");
                h += q.charAt(i + 1);
            }
            i++;
            c = q.charAt(i);
        }
        result = Double.parseDouble(h);
    } catch (Exception e) {
        Log.i("MyApps", "Index is out of bounds");
    }
}

2 个答案:

答案 0 :(得分:3)

你会尝试这样的事情:

public static void main(String[] args) {
        String str = "dsde1121zszs.15szs"; 
        Double d = Double.valueOf(str.replaceAll("[^0-9\\.]", ""));
        System.out.println(d);
    }

答案 1 :(得分:0)

您应该使用DecimalFormat并避免创建自己的解析器实现。有关示例,请参阅此question

相关问题