首页 > 编程知识 正文

bigdecimal四舍五入,bigdecimal加法运算

时间:2023-05-04 08:27:07 阅读:128078 作者:2175

BigDecimal有四种构建方法,其中两种用BigInteger构建,一种用double构建,另一种用String构建。

应该避免使用双精度构建BigDecimal。 之所以这么说,是因为double有无法准确表达的数字,传递给BigDecimal后就不准确了。

例如,newbigdecimal(0.1 )获得的值为0.1000000000051151231257827021183404541015625

使用newBigDecimal('0.1 ' )得到的值为0.1。

因此,如果需要精确的计算,请不要使用Sring构建BigDecimal,而不要使用双精度。 但是,看起来更简单。

equals ) )方法返回true,假设0.1和0.1相等,如果0.10和0.1不同,则返回false。

比较到(方法假设0.1等于0.1,0.10和0.1也相等。 因此,在数值上比较两个BigDecimal值时,

必须使用equals (比较到) (而不是)。

另外,任意精度的小数运算也可能得不到正确的结果。

例如,1除以9可以生成无限循环的小数,0.11111111111 .

因此,使用BigDecimal可以在除法时显式控制舍入。

publicclassaccuratelyfloat { publicstaticvoidmain [ ] args } {双门=2; //现有金额double price=1.1; //商品价格double result=money - price; 双添加=money price; doublemultiplicative=money * price; 双器件=money/price; System.out.println (非严格计算); System.out.println ('剩余金额: ' result '//输出运算结果System.out.println ('总额: ' add ) ); //输出运算结果的System.out.println ()相乘金额: ' multiplicative ); //输出运算结果的System.out.println ('除法金额:“divide”); //输出运算结果//正确浮点数的解决方法bigdecimal money1=new bigdecimal ('2); bigdecimal price1=new bigdecimal (' 1.1 ); bigdecimal result1=money1. subtract (price1); //BigDecimal减法,相当于result1- price1bigdecimal add1=money1. add (price1); //BigDecimal加法,相当于result1price1bigdecimalmultiplicative1=money1. multiply (price1); //BigDecimal乘法,相当于result1* price1bigdecimal divide1=money1. divide (price1); //BigDecimal除法相当于result1/price1system.out.println (精确计算)。 System.out.println ('剩余金额: ' result1' system.out.println ('总额: ' add1) ); System.out.println ('乘法金额: ' multiplicative1); System.out.println (相除金额: ' divide1); }上的代码在执行中报告异常的异常如下。

exceptioninthread ' main ' Java.lang.arithmetic exception 3360 non-terminatingdecimalexpansion; noexactrepresentabledecimalresult。

此异常是BigDecimal类的divide ) )方法的结果是无限小数导致的异常。

double divide1=money1. divide (price 1,2,BigDecimal.ROUND_DOWN ).doubleValue ); //BigDecimal除法相当于result1/price1更改此行的代码不会引发异常,执行结果如下。

不准确的计算

剩余金额: 0.8999999999999999

总额: 3.1

乘法金额: 2.2

相除金额: 1.81818181818181818181

正确计算

剩余金额: 0.9

总额: 3.1

乘法金额: 2.2

相除金额: 1.81

转载于:https://my.oschina.net/u/3268723/blog/889125

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。