验证字符串是否为数字(字符串能否转为整数或小数)

在实际开发中,我们时常面临将客户端发送的字符串数据转换为数字的情况,如果不做判断,直接使用java方法转换的话,可能会报类型转换异常(客户输入的数据不是数字),所以一定要做字符串数据的判断

方法一:判断字符串是否为整数

  public static boolean isNumericInt(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
  }

方法二:判断字符串是否为整数或者小数

    public static boolean isNumeric(String str){

        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;


    }

如果以上方法返回的值为true,则可以进行下一步操作,比如将字符串转化为整数: Integer.parseInt(str),或者将字符串转化为小数: Double.valueOf(str)。

猜你喜欢

转载自www.cnblogs.com/lychngdesign/p/12935033.html