[英]How do I properly parse a string with a float values with a given number of decimal places into an integer?
[英]How do I parse a String to get the decimal and a word with a dot properly?
如何區分找到小數點的區別,但如果是句點,則同時忽略它?
例如,假設掃描儀
String s = "2015. 3.50 please";
當我使用功能scanner.hasNextFloat()
,如何忽略Hi。 ?
我只掃描1行。 我需要確定一個單詞是字符串,整數還是浮點數。 我的最終結果應如下所示:
This is a String: 2015.
This is a float: 3.50
This is a String: please
但是在我使用scanner.hasNextFloat();
將2015年標識為浮動。
在Java中,您可以使用正則表達式。 一個或多個數字,然后是文字點,然后是兩個數字。 就像是
String s = "Hi. 3.50 please";
Pattern p = Pattern.compile(".*(\\d+\\.\\d{2}).*");
Matcher m = p.matcher(s);
Float amt = null;
if (m.matches()) {
amt = Float.parseFloat(m.group(1));
}
System.out.printf("Ammount: %.2f%n", amt);
輸出是
Ammount: 3.50
我假設您的意思是Java,因為javascript沒有Scanner。
String s = "Hi. 3.50 please";
Scanner scanner = new Scanner(s);
while (scanner.hasNext()){
if (scanner.hasNextInt()){
System.out.println("This is an int: " + scanner.next());
} else if (scanner.hasNextFloat()){
System.out.println("This is a float: " + scanner.next());
} else {
System.out.println("This is a String: " + scanner.next());
}
}
輸出:
This is a String: Hi.
This is a float: 3.50
This is a String: please
所以有什么問題?
您可以使用正則表達式來匹配數字
String[] str = { " Hi, My age is 12", "I have 30$", "Eclipse version 4.2" };
Pattern pattern = Pattern.compile(".*\\s+([0-9.]+).*");
for (String string : str) {
Matcher m = pattern.matcher(string);
System.out.println("Count " + m.groupCount());
while (m.find()) {
System.out.print(m.group(1) + " ");
}
System.out.println();
}
輸出:
Count 1 12 Count 1 30 Count 1 4.2
如果數字可以具有e
或E
[0-9.eE]
,則在模式String中添加[0-9.eE]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.