1

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");
    }
}
brimborium
  • 9,362
  • 9
  • 48
  • 76
  • What format does your `String` have? Maybe you just need to `trim()` or clean it up before the call to `Double.parseDouble()`. – Keppil Jul 24 '12 at 09:45

2 Answers2

3

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);
    }
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0

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

Community
  • 1
  • 1
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194