7

I have a string like

> 12.4N-m/kg.

From the above string I need to get a value 12.4.

When I use replace all function str.replaceAll("[^.0-9]", "").

This doesn't work when then string has two dots.

The location of float value may differ.

user1773765
  • 75
  • 1
  • 1
  • 4

7 Answers7

12

First discard all non flot characters and then covert to Float like this:

float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
// now f = 12.4
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Can you please explain the meaning of the pattern [^\\d.]+|\\.(?!\\d) ?? if possible, could you explain the process of identifying the patterns for given input? – Munesh Oct 25 '12 at 12:05
  • 3
    Sure @Munesh: That regex: `[^\\d.]+|\\.(?!\\d)` means that it is matching one of 2 sub regex on either side of pipe `|`. LHS matches anything except digit or perios whereas RHS means a period which is **NOT** followed by a digit using negative lookahead. – anubhava Oct 25 '12 at 12:20
  • 1
    Thanks anubhava. It would be helpful if you add this explanation in the answer. – Munesh Oct 25 '12 at 12:27
  • 1
    Great answer :) – Manuli Aug 24 '17 at 06:04
2

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

String t = "> 12.4N-m/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)));
}
0

Try to use this:

Float.valueOf(str.substring(0,4));
hoang nguyen
  • 2,119
  • 5
  • 21
  • 20
0

following code will work with assumption that input string always starts with "> " and it has proper float prefixed.

int i=2;
while(Character.isDigit(str.charAt(i)) || str.charAt(i) == '.') 
    i++;
float answer = Float.valueOf(str.substring(2,i));
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

Try to use this regular expression

^[-+]?[0-9]*\.?[0-9]+$
Valeriy Gorbatikov
  • 3,459
  • 1
  • 15
  • 9
0

I think the previous answers leave out two points:

  • There are more complicated numbers than this.
  • There might be a digit in the unit which souldn't end up in the float.

Because of the second point I don't think replacing everything that is a non-digit is a good idea. One should rather search 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 could 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 a helper

private static boolean mightBePartOfNumber(char c) {
    return ('0' <= c && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'; 
}       
chs
  • 652
  • 4
  • 17
0

I have tried the above options but not worked for me , Please try below pattern

Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?");
Helping Hands
  • 5,292
  • 9
  • 60
  • 127