版权声明:本文为博主原创文章,转载请指明出处。 https://blog.csdn.net/baidu_32739019/article/details/79625698
在处理BigDecimal 对象的 数值相加的问题上遇到麻烦,借鉴了 JAVA BigDecimal的相加 的文章,但是依然没有解决我的问题。
其文章分析如下(纯属借鉴!)
代码如下:
- BigDecimal totalAmount = new BigDecimal(0);
- totalAmount.add(new BigDecimal(5000));
- System.out.println(totalAmount);
输出结果为0。
查资料后才知道,要这样写才行:
- BigDecimal totalAmount = new BigDecimal(0);
- totalAmount = totalAmount.add(new BigDecimal("5000"));
- System.out.println(totalAmount);
同时,在new一个BigDecimal对象的时候,最好传入字符串或者int类型的数字,因为传入double类型的数字会有很神奇的事情发生,
比如说:
- BigDecimal totalAmount = new BigDecimal(0);
- totalAmount = totalAmount.add(new BigDecimal(0.59));
- System.out.println(totalAmount);
输出结果:
0.58999999999999996891375531049561686813831329345703125
但是如果传入的是String类型的数字:
- BigDecimal totalAmount = new BigDecimal(0);
- totalAmount = totalAmount.add(new BigDecimal("0.59"));
- System.out.println(totalAmount);
输出结果:
0.59
上自己的:
BigDecimal productAmount = new BigDecimal(20);
BigDecimal taxAmount = new BigDecimal(2.38);
BigDecimal shippingAmount = new BigDecimal(0);
BigDecimal totalAmount = new BigDecimal(0);
totalAmount = totalAmount.add(new BigDecimal("" + productAmount.toString()));
totalAmount = totalAmount.add(new BigDecimal("" + taxAmount.toString()));
totalAmount = totalAmount.add(new BigDecimal("" + shippingAmount.toString()));
String priceVal = new java.text.DecimalFormat("######0.00")
.format(totalAmount.setScale(2, BigDecimal.ROUND_UP).doubleValue());
System.out.println(priceVal.toString());
这样写就完美的解决了我自己的问题!
详细请参照此文:BigDecimal 的那些坑事儿