import java.math.BigDecimal;
public class BigDecimalToIntegerExample {
    public static void main(String[] args) {
        // 创建一个BigDecimal对象
        BigDecimal bigDecimal = new BigDecimal("123.45");
        // 方法1: 使用intValue()方法将BigDecimal转换为int
        int intValue = bigDecimal.intValue();
        System.out.println("Using intValue(): " + intValue);
        // 方法2: 使用intValueExact()方法将BigDecimal转换为int,会抛出异常如果存在精度损失
        try {
            int intValueExact = bigDecimal.intValueExact();
            System.out.println("Using intValueExact(): " + intValueExact);
        } catch (ArithmeticException e) {
            System.out.println("intValueExact() threw an ArithmeticException because of precision loss.");
        }
        // 方法3: 先使用setScale()方法四舍五入,再使用intValue()方法
        BigDecimal roundedBigDecimal = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP);
        int roundedIntValue = roundedBigDecimal.intValue();
        System.out.println("Rounded using setScale() and intValue(): " + roundedIntValue);
    }
}
intValue():
BigDecimal 转换为 int 类型。如果有小数部分,它会直接截断(即丢弃小数部分),不会进行四舍五入。123.45 会被转换为 123。intValueExact():
intValue() 类似,但它会在转换时检查是否有精度损失。如果有精度损失(即有小数部分),它会抛出 ArithmeticException。123.45 会抛出异常,而 123.0 则可以成功转换为 123。setScale() 和 intValue() 结合使用:
BigDecimal 进行四舍五入后再转换为 int,可以先使用 setScale() 方法指定小数位数和舍入模式,然后再调用 intValue()。123.45 通过 setScale(0, BigDecimal.ROUND_HALF_UP) 后变为 123,再通过 intValue() 转换为 123。希望这些代码和解释对你有帮助!
上一篇:java break跳出几层循环
下一篇:java判断两个日期相差多少天
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站