使用BigDecimal数舍入是必需的 [英] Rounding necessary with BigDecimal numbers

查看:54
本文介绍了使用BigDecimal数舍入是必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置两个BigDecimal数字ab的小数位数.如本例所示:

I want to set scale of two BigDecimal numbers a and b . as in this example :

BigDecimal a = new BigDecimal("2.6E-1095");
        BigDecimal b = new BigDecimal("2.7E-1105");
        int i = 112, j=1;

        BigDecimal aa = a.setScale(i+j);
        BigDecimal bb = b.setScale(i+j);

当我运行时,我会遇到以下例外情况:

and when i run i have this exception:

java.lang.ArithmeticException: Rounding necessary
    at java.math.BigDecimal.divideAndRound(BigDecimal.java:1439)
    at java.math.BigDecimal.setScale(BigDecimal.java:2394)
    at java.math.BigDecimal.setScale(BigDecimal.java:2437)

为什么需要四舍五入?如果我不想解决问题,请问解决方案是什么?

Why rounding is necessary ? if i don't want to make around, what is solution please ?

谢谢

推荐答案

您有两个BigDecimal数字,它们都需要超过1000个小数位.尝试将小数位设置为只有113个小数位意味着您将失去精度,因此需要四舍五入.

You have two BigDecimal numbers both of which require over a 1000 decimal places. Trying to set the scale to only have 113 decimal places means you will lose precision and therefore you need to round.

您可以使用采用RoundingMode的setScale方法来防止发生异常,但不能避免四舍五入.

You can use the setScale methods that take a RoundingMode to prevent the exception but not the rounding.

这篇关于使用BigDecimal数舍入是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆