BigDecimal类型转换成Integer类型,下面为你介绍这两种方
分享于 点击 29267 次 点评:178
BigDecimal类型转换成Integer类型,下面为你介绍这两种方
在 Java 里,若要把BigDecimal
类型转换为Integer
类型,可借助intValue()
或者intValueExact()
方法。下面为你介绍这两种方法的具体使用以及它们之间的差异。
1. 采用intValue()
方法(不进行溢出检查)
这种方法会把BigDecimal
转换为int
基本类型,要是BigDecimal
超出了int
的范围,就会对结果进行截断处理。
import java.math.BigDecimal; public class BigDecimalToIntegerExample { public static void main(String[] args) { // 示例1:数值在int范围内 BigDecimal bd1 = new BigDecimal("12345"); int intValue1 = bd1.intValue(); Integer integer1 = Integer.valueOf(intValue1); System.out.println("转换结果1: " + integer1); // 输出: 12345 // 示例2:数值超出int范围(会进行截断) BigDecimal bd2 = new BigDecimal("2147483648"); // 比Integer.MAX_VALUE大1 int intValue2 = bd2.intValue(); // 截断后会得到一个负数 Integer integer2 = Integer.valueOf(intValue2); System.out.println("转换结果2: " + integer2); // 输出: -2147483648 } }
2. 使用intValueExact()
方法(进行溢出检查)
该方法在BigDecimal
的值超出int
范围时,会抛出ArithmeticException
异常。
import java.math.BigDecimal; import java.math.ArithmeticException; public class BigDecimalToIntegerExactExample { public static void main(String[] args) { try { // 示例1:数值在int范围内 BigDecimal bd1 = new BigDecimal("12345"); int intValue1 = bd1.intValueExact(); Integer integer1 = Integer.valueOf(intValue1); System.out.println("转换结果1: " + integer1); // 输出: 12345 // 示例2:数值超出int范围(会抛出异常) BigDecimal bd2 = new BigDecimal("2147483648"); int intValue2 = bd2.intValueExact(); // 这里会抛出ArithmeticException Integer integer2 = Integer.valueOf(intValue2); System.out.println("转换结果2: " + integer2); } catch (ArithmeticException e) { System.out.println("错误: " + e.getMessage()); // 输出: 错误: Overflow } } }
方法选择建议
自动装箱说明
在上述示例中,我们先把BigDecimal
转换为int
基本类型,再通过Integer.valueOf(int)
将其转换为Integer
对象。其实也可以利用 Java 的自动装箱机制,直接把int
赋值给Integer
,例如:
Integer integer = bd.intValue(); // 自动装箱
处理小数部分
要是BigDecimal
包含小数部分,上述两种方法都会直接舍弃小数部分(并非四舍五入)。例如:
BigDecimal bd = new BigDecimal("12.9"); int result = bd.intValue(); // 结果为12
如果你需要进行四舍五入,可以先使用setScale()
方法进行处理:
BigDecimal bd = new BigDecimal("12.9"); BigDecimal rounded = bd.setScale(0, BigDecimal.ROUND_HALF_UP); // 四舍五入为13 int result = rounded.intValueExact(); // 结果为13
用户点评