您的位置 首页 java

Java中如何检查字符串是否为数字?

数字在Java中分为:int – 整型,long – 长整型,float – 浮点型,double – 双精度浮点型。

Talk is cheap, Show me the code. — by: Linus Torvalds

方式一、

try catch 法,4种类型中 double 能表示的范围最大,可以使用Double.parseDouble()进行转换,出现异常说明不是数字,代码如下:

 public static boolean isNum(String str) {
    boolean b = false;
    try {
        Double.parseDouble(str);
        b = true;
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return b;
}  

方式二、

使用正则表达,代码如下:

 public static boolean isNum(String str) {
    return str.matches("\\d+(\\.\\d+)?");
}  

方式三、

使用commons-lang3,测试版本为:3.11

 // 此方式只能判断:int 和 long
System.out.println(StringUtils.isNumeric("123")); // true
System.out.println(StringUtils.isNumeric("123.3")); // false
System.out.println(StringUtils.isNumericSpace("23")); // true
System.out.println(StringUtils.isNumericSpace("23.3")); // false  

文章来源:智云一二三科技

文章标题:Java中如何检查字符串是否为数字?

文章地址:https://www.zhihuclub.com/185642.shtml

关于作者: 智云科技

热门文章

网站地图