当我运行这行代码时: Float.parseFloat("1460000 JPY") 我收到错误
线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:“1460000 JPY”
此字符串来自表单的 API 调用,其中这是一个没有验证的文本字段。它通常有效,因为人们只输入了一个数字,但有时你会遇到这个问题。如何让它只返回初始数字作为浮点数并忽略尾随的字母字符?
当我运行这行代码时: Float.parseFloat("1460000 JPY") 我收到错误
线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:“1460000 JPY”
此字符串来自表单的 API 调用,其中这是一个没有验证的文本字段。它通常有效,因为人们只输入了一个数字,但有时你会遇到这个问题。如何让它只返回初始数字作为浮点数并忽略尾随的字母字符?
您可以使用正则表达式来查找该字符串是否仅包含数字
String apistring = "1460000 JPY";
if(apistring.matches("[0-9]+")){
// do your code
}else{
// throw some error message
}
从中剥离 char 将很困难,因为您说它是一个输入字段,用户可以输入任何文本。仅当您知道存在特定模式时才能将其剥离
由于DecimalFormat
对解析字符串非常宽松,我建议这样做。
你可以像这样使用它:
DecimalFormat df = new DecimalFormat();
try {
float parsedValue = df.parse("1460000 JPY").floatValue();
System.out.println(parsedValue);
} catch (ParseException pe) {
pe.printStackTrace();
// handle exception a bit more
}
这打印:
1460000.0
As you can see the parse
method can throw a ParseException
if the passed String starts with something else than a number, like:
blub 1460000 JPY
If that won't happen in your app, then you don't have to bother about it.
You can use regex to extract the numbers in input .
s = s.replaceAll("[^0-9]","");
and then parse float from it. Only downside is that it will extract all numbers (It will extract 1245 and 3 both from 1245 JPY 3).
更新:解释@Tom 提出的错误:
Float.parseFloat("1.46 JPY".replaceAll("[^0-9.]",""));
1.46
以上是一个优越的解决方案。请参阅下面的说明。
正如@azurefrog 所说,去掉非数字字符,然后将剩下的内容解析为 aFloat
是可行的方法。您可以使用以下代码完成此操作:
Float.parseFloat("1460000 JPY".replaceAll("[^0-9]",""));
1460000.0
虽然这不是很健壮,因为对于像"1.46"
输出这样的输入来说
146.0
.replaceAll("[^0-9.]","")
.
通过像这样将十进制字符添加到排除正则表达式来修复这种不准确性[^0-9.]