Non-terminating decimal expansion; no exact representable decimal result.

Non-terminating decimal expansion; no exact representable decimal result.

        BigDecimal b1=new BigDecimal(1);
        BigDecimal b2=new BigDecimal(3);
        BigDecimal b3=b1.divide(b2);

报错

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

BigDecimal 用于高精度的数学计算,这个异常翻译

java.lang.AthmeticException:非终止小数展开;没有可精确表示的十进制结果。

意思就是这个除法除不尽,会得到一个无限小数,导致异常。

解决办法:

       BigDecimal b3=b1.divide(b2,2, RoundingMode.HALF_UP);

2表示保留2位小数
RoundingMode.HALF_UP 表示四舍五入。

setScale

设置精度

        Double d = 111.123456;
        BigDecimal bd = new BigDecimal(d);
        BigDecimal bd1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP);//111.12

表示保留2位小数,四舍五入。

DecimalFormat

格式换转换为字符串,设置保留精度

        Double d = 111.123456;
        BigDecimal bd = new BigDecimal(d);
        DecimalFormat df = new DecimalFormat("#0.00");
        String str1 = df.format(bd);
        System.out.println(str1);//111.12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值