当前位置: 代码迷 >> 综合 >> 使用 StringUtils.isNumeric(str) 判断是否为数字
  详细解决方案

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

热度:65   发布时间:2023-11-27 01:36:08.0

今天在项目中遇到个 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)); // falseSystem.out.println("传入空字符串输出的结果为:" + StringUtils.isNumeric("")); // falseSystem.out.println("传入空格输出的结果为:" + StringUtils.isNumeric(" ")); // falseSystem.out.println("传入0输出的结果为:" + StringUtils.isNumeric("0")); // trueSystem.out.println("传入数字带空格输出的结果为:" + StringUtils.isNumeric(" 0")); // falseSystem.out.println("传入负数输出的结果为:" + StringUtils.isNumeric("-10")); // falseSystem.out.println("传入小数输出的结果为:" + StringUtils.isNumeric("1.0")); // falseSystem.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 这个数值工具类中的一些方法也是不错的选择

  相关解决方案