简体   繁体   中英

extracting a double value from a string of alphanumeric characters in Java

I'm looking for a function that does what the heading says.

I ended up with writing code that parses through every character and making another string then Double.parseDouble . Which threw StringIndexoutOfBounds exception. Which is clearly not the way to go.

The block of code is here

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

You would try something like this:

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

You should use DecimalFormat and avoid creating your own implementation of a parser. See this question for some examples.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM