I think the previous answers left two points:
- There are more complex numbers than that.
- There may be a number in the module that cannot get into the float.
Because of the second point, I do not think that replacing everything that is not a number is a good idea. Rather, look for the first number in the string:
Matcher m = p.matcher(str); System.out.println("Input: "+ str); if (m.find()) { System.out.println("Found: "+ m.group()); try { System.out.println("Number: "+ Float.parseFloat(m.group())); } catch (Exception exc) { exc.printStackTrace(); } }
Alternatively, you can do something like
int i, j; for (i = 0; i < str.length(); ++i) { if (mightBePartOfNumber(str.charAt(i))) { break; } } for (j = i; j < str.length(); ++j) { if (!mightBePartOfNumber(str.charAt(j))) { break; } } String substr = str.substring(i, j); System.out.println("Found: "+ substr); try { System.out.println("Number: "+ Float.parseFloat(substr)); } catch (Exception exc) { exc.printStackTrace(); }
with assistant
private static boolean mightBePartOfNumber(char c) { return ('0' <= c && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'; }
chs
source share