使用 StringUtils.isNumeric(str) 判断是否为数字

Posted 思想累积

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 StringUtils.isNumeric(str) 判断是否为数字相关的知识,希望对你有一定的参考价值。

今天在项目中遇到个 bug,发现问题出现在 org.apache.commons.lang3.StringUtils.isNumeric(str) 身上了,代码是需要判断一个参数为正整数

if(StringUtils.isNotBlank(str) && !StringUtils.isNumberic(str)) {
    // ......
}

原先我采用的正则表达式进行判断的,后面别人进行了改动(为啥改动?),使用了这个方法,发现这个!StringUtils.isNumberic(str) 判断字符串为 0 的时候会为 false。。。

下面进行一些测试,看看 StringUtils.isNumberic(str) 可以做一些什么事

导入 maven 依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>{commons-lang3.version}</version>
</dependency>

测试用例:

@Test
void contextLoads() {
    System.out.println("传入null输出的结果为:" + StringUtils.isNumeric(null)); // false
    System.out.println("传入空字符串输出的结果为:" + StringUtils.isNumeric("")); // false
    System.out.println("传入空格输出的结果为:" + StringUtils.isNumeric(" ")); // false
    System.out.println("传入0输出的结果为:" + StringUtils.isNumeric("0")); // true
    System.out.println("传入数字带空格输出的结果为:" + StringUtils.isNumeric(" 0")); // false
    System.out.println("传入负数输出的结果为:" + StringUtils.isNumeric("-10")); // false
    System.out.println("传入小数输出的结果为:" + StringUtils.isNumeric("1.0")); // false
    System.out.println("传入正整数输出的结果为:" + StringUtils.isNumeric("10")); // true
}

源码

public static boolean isNumeric(final CharSequence cs) {
    if (isEmpty(cs)) {
        return false;
    }
    final int sz = cs.length();
    for (int i = 0; i < sz; i++) {
        if (!Character.isDigit(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}

点进去发现还是比较简单的,使用了 Character.isDigit(char) 方法判断指定字符是不是一个数字

这个方法挺好用的,可是它判断是是否为数字呀,最后还得再加上不为 0 的判断,果然还是代码能跑就不要随便改了,bug 就是这么出来的。

如果想要对数字进行操作的话,使用 org.apache.commons.lang3.math.NumberUtils 这个数值工具类中的一些方法也是不错的选择

以上是关于使用 StringUtils.isNumeric(str) 判断是否为数字的主要内容,如果未能解决你的问题,请参考以下文章

测试使用

第一篇 用于测试使用

在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?

今目标使用教程 今目标任务使用篇

Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)

MySQL db 在按日期排序时使用“使用位置;使用临时;使用文件排序”