如何从字符串中获取浮点值

时间:2021-11-17 20:55:10

I have a string like

我有一根像绳子的

> 12.4N-m/kg.

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

从上面的字符串中,我需要得到一个值12.4。

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

当我使用替换所有函数str.replaceAll(“(^。0 - 9]”、“”)。

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

当弦有两个点时,这个就不成立了。

The location of float value may differ.

浮动值的位置可能不同。

7 个解决方案

#1


11  

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

首先丢弃所有非flot字符,然后隐藏如下:

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

#2


2  

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

假设你的输入总是在数字前有一个空格,在数字后有一个N:

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

#3


0  

Try to use this:

尝试使用:

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

#4


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

#5


0  

Try to use this regular expression

尝试使用这个正则表达式

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

#6


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

#7


0  

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

我已经尝试了以上的选项,但是没有为我工作,请尝试下面的模式。

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

#1


11  

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

首先丢弃所有非flot字符,然后隐藏如下:

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

#2


2  

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

假设你的输入总是在数字前有一个空格,在数字后有一个N:

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

#3


0  

Try to use this:

尝试使用:

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

#4


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

#5


0  

Try to use this regular expression

尝试使用这个正则表达式

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

#6


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

#7


0  

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

我已经尝试了以上的选项,但是没有为我工作,请尝试下面的模式。

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