BigDecimal精确到几位以及四舍五入



//BigDecimal流reduce()进行累加
BigDecimal stoNum = entry.getValue().stream()
.map(order -> new BigDecimal(order.getStorageNum()).multiply(new BigDecimal(order.getSellPrice() == null ? "0.00" : order.getSellPrice())))
.reduce(new BigDecimal(0), BigDecimal::add);






BigDecimal result = null;
//判断结果是否为零
BigDecimal bigDecimalZero = BigDecimal.ZERO.setScale(8, BigDecimal.ROUND_HALF_UP);

String str = String.valueOf(stoNum.toPlainString());
int length = str.substring(str.indexOf(".") + 1, str.length()).length();
if(length>8){
//小数点后大于八位四舍五入
result = stoNum.setScale(8, BigDecimal.ROUND_HALF_UP);
}else{
//小数点后不足8位小数补0
result=new BigDecimal(new DecimalFormat("0.00000000#").format(stoNum));
}
System.out.println("值为: = " + result);
posted @ 2021-04-03 14:29  回忆往事2  阅读(509)  评论(0编辑  收藏  举报