[java]判断字符串是否为数字类型
2013-12-19 11:41 mjsmove 阅读(318) 评论(0) 收藏 举报几个常规的判断方法:
public static boolean isNumeric_1(String str) {
for (int i = str.length(); --i >= 0;) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isNumeric_2(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isNumeric_3(String str) {
for (int i = str.length(); --i >= 0;) {
int chr = str.charAt(i);
if (chr < 48 || chr > 57)
return false;
}
return true;
}
都没法判断字符串是不是负数字符串或小数的字符串。
后来又从stackoverflow上找到一方法,可以判断小数或负数:
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
浙公网安备 33010602011771号