在 Java 中从字符串中获取 Double
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10971072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Double from string in Java
提问by kande
I have a text (String) an I need to get only digits from it, i mean if i have the text:
我有一个文本(字符串),我只需要从中获取数字,我的意思是如果我有文本:
"I'm 53.2 km away", i want to get the "53.2" (not 532 or 53 or 2)
“我在 53.2 公里外”,我想得到“53.2”(不是 532 或 53 或 2)
I tried the solution in Extract digits from a string in Java. it returns me "532".
我尝试了从 Java 中的字符串中提取数字中的解决方案。它返回我“532”。
Anyone have an idea for it?
有没有人对此有想法?
Thanx
谢谢
回答by Suraj Chandran
You can directly use a Scannerwhich has a nextDouble()
and hasNextDouble()
methods as below:
您可以直接使用扫描仪具有nextDouble()
和hasNextDouble()
方法如下:
Scanner st = new Scanner("I'm 53.2 km away");
while (!st.hasNextDouble())
{
st.next();
}
double value = st.nextDouble();
System.out.println(value);
Output: 53.2
输出:53.2
回答by dantuch
Here is good regex site with tester:
这是带有测试仪的良好正则表达式站点:
this works fine \d+\.?\d+
这工作正常 \d+\.?\d+
回答by Surender Thakran
import java.util.regex.*;
class ExtractNumber
{
public static void main(String[] args)
{
String str = "I'm 53.2 km away";
String[] s = str.split(" ");
Pattern p = Pattern.compile("(\d)+\.(\d)+");
double d;
for(int i = 0; i< s.length; i++)
{
Matcher m = p.matcher(s[i]);
if(m.find())
d = Double.parseDouble(m.group());
}
System.out.println(d);
}
}
回答by Amimo Benja
The best and simple way is to use a regex expression and the replaceAll string method. E.g
最好且简单的方法是使用正则表达式和 replaceAll 字符串方法。例如
String a = "2.56 Kms";
String b = a.replaceAll("\^[0-9]+(\.[0-9]{1,4})?$","");
Double c = Double.valueOf(b);
System.out.println(c);
回答by Chu Vu Hung
I have just made a method getDoubleFromString. I think it isn't best solution but it works good!
我刚刚创建了一个方法 getDoubleFromString。我认为这不是最好的解决方案,但效果很好!
public static double getDoubleFromString(String source) {
if (TextUtils.isEmpty(source)) {
return 0;
}
String number = "0";
int length = source.length();
boolean cutNumber = false;
for (int i = 0; i < length; i++) {
char c = source.charAt(i);
if (cutNumber) {
if (Character.isDigit(c) || c == '.' || c == ',') {
c = (c == ',' ? '.' : c);
number += c;
} else {
cutNumber = false;
break;
}
} else {
if (Character.isDigit(c)) {
cutNumber = true;
number += c;
}
}
}
return Double.parseDouble(number);
}
回答by nbarraille
If you know for sure your numbers are "words" (space separated) and don't want to use RegExs, you can just parse them...
如果您确定您的数字是“单词”(空格分隔)并且不想使用正则表达式,您可以解析它们......
String myString = "I'm 53.2 km away";
List<Double> doubles = new ArrayList<Double>();
for (String s : myString.split(" ")) {
try {
doubles.add(Double.valueOf(s));
} catch (NumberFormatException e) {
}
}