可以利用正则表达式来“-?[0-9]+(.[0-9]+)?
”来做判断字符串是否为数字。
如果传入的数据有很多位,那么使用double会导致精度丢失,这个时候就要用BigDecimal来进行转换。
实例:
public class CheckStrIsNum {
public static void main(String[] args) {
double aa = -192322.1212;
String a = "-192322.1212";
String b = "-192322a1212";
String c = "Java";
String d = "5";
System.out.println(checkStrIsNum02(Double.toString(aa)));
System.out.println(checkStrIsNum02(a));
System.out.println(checkStrIsNum02(b));
System.out.println(checkStrIsNum02(c));
System.out.println(checkStrIsNum02(d));
}
private static Pattern NUMBER_PATTERN = Pattern.compile("-?[0-9]+(.[0-9]+)?");
public static boolean checkStrIsNum02(String str) {
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;
}
Matcher isNum = NUMBER_PATTERN.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
推荐教程:java开发入门