How to get float value from string

I have a line like

> 12.4Nm/kg. 

From the line above, I need to get the value 12.4 .

When I use the replacement of the entire function str.replaceAll("[^.0-9]", "") .

This does not work when the line has two points.

The location of the float value may vary.

+7
source share
7 answers

First discard all characters without a fleet, and then hidden on the float, like this:

 float f = Float.valueOf("> 12.4Nm/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", "")); // now f = 12.4 
+10
source

Assuming your input always has a space before the number and N after it:

 String t = "> 12.4Nm/kg."; Pattern p = Pattern.compile("^.*\\s(\\d+\\.\\d)N.*$"); Matcher matcher = p.matcher(t); if (matcher.matches()) { System.out.println(Float.valueOf(matcher.group(1))); } 
+2
source

Try using this:

 Float.valueOf(str.substring(0,4)); 
0
source

The following code will work under the assumption that the input line always starts with "> " and has the correct floating point prefix.

 int i=2; while(Character.isDigit(str.charAt(i)) || str.charAt(i) == '.') i++; float answer = Float.valueOf(str.substring(2,i)); 
0
source

Try using this regex

 ^[-+]?[0-9]*\.?[0-9]+$ 
0
source

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'; } 
0
source

I tried the above options but didn't work for me. Please try the picture below.

 Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?"); 
0
source

All Articles