通用的数字转换工具类

Java 语言中有一个通用的数字转换工具类 org.apache.commons.lang3.math.NumberUtils,它提供了很多关于数字类型转换等操作的方法。需要导入 Apache Commons Lang 3 库才能使用该工具类,可以通过 Maven 或 Gradle 在项目中添加以下依赖:

Maven:

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

Gradle:

implementation 'org.apache.commons:commons-lang3:3.13.0'

通过 org.apache.commons.lang3.math.NumberUtils 可以进行如下的类型转换:

  1. toXXX(String str): 将字符串类型转换为指定数字类型 XXX,比如 toInt(String str)toLong(String str)toDouble(String str) 等。
  2. isCreatable(String str): 判断一个字符串是否可以创建为数字。如果字符串为 null 或 “”,则返回 false。
  3. isDigits(String str): 判断一个字符串是否全由数字组成。
  4. compare(Number x, Number y): 比较两个数字类型的大小,返回值为 -1(x 小于 y)、0(x 等于 y)、1(x 大于 y)。

以下是一个示例代码:

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtilsDemo {
    public static void main(String[] args) {
        String str = "123";
        int intValue = NumberUtils.toInt(str);
        boolean isDigits = NumberUtils.isDigits(str);
        System.out.println("intValue: " + intValue); // 输出: 123
        System.out.println("isDigits: " + isDigits); // 输出: true
        System.out.println(NumberUtils.toInt(null, 0));//输出0
    }
}

需要注意的是,虽然使用 org.apache.commons.lang3.math.NumberUtils 可以简化我们的代码,但是在实际使用过程中,还是需要注意数据类型转换造成的风险,避免数据溢出等问题

posted @ 2023-04-14 21:45  进击的小蔡鸟  阅读(66)  评论(0编辑  收藏  举报