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

createh54个月前 (12-13)技术教程48

数字在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判断字符串是否为数字的几种方式

一,使用StringUtils工具类;通过StringUilts工具包进行判断:org.apache.commons.lang3.StringUtils提供了丰富的字符串解析的工具包,其中isNume...

为何String 会不可变?难道真的是因为 final 吗?

String 为啥不可变?因为 String 中的 char 数组被 final 修饰。这套回答相信各位已经背烂了,But 这并不正确!面试官:讲讲 String、StringBuilder、Stri...

Java分割字符串(spilt())

String 类的 split() 方法可以按指定的分割符对目标字符串进行分割,分割后的内容存放在字符串数组中。该方法主要有如下两种重载形式:其中它们的含义如下:str 为需要分割的目标字符串。sig...