String转BigDecimal,BigDecimal常用操作,以及避免踩坑

String转BigDecimal

String a = "50.00";  //字符串类型,必须是数字,否则会报错, java.lang.NumberFormatException 异常
BigDecimal b =new BigDecimal(a);

BigDecimal加法运算

BigDecimal planeTax=new BigDecimal(bookInfo.getPlaneTax());
BigDecimal yq=new BigDecimal(bookInfo.getYq());
BigDecimal publishPrice =  new BigDecimal(cabinInfo.getPublishPrice());
totalPrice =publishPrice.add(planeTax).add(yq);

BigDecimal减法运算

BigDecimal planeTax=new BigDecimal(bookInfo.getPlaneTax());
BigDecimal yq=new BigDecimal(bookInfo.getYq());
BigDecimal publishPrice =  new BigDecimal(cabinInfo.getPublishPrice());
totalPrice =publishPrice.subtract(planeTax).subtract(yq);

BigDecimal乘法运算

BigDecimal planeTax=new BigDecimal(bookInfo.getPlaneTax());
BigDecimal yq=new BigDecimal(bookInfo.getYq());
BigDecimal publishPrice =  new BigDecimal(cabinInfo.getPublishPrice());
totalPrice =publishPrice.multiply(planeTax).multiply(yq);

BigDecimal避免踩坑

 

BigDecimal planeTax=new BigDecimal(bookInfo.getPlaneTax());//string数据转换BigDecimal
  BigDecimal yq=new BigDecimal(bookInfo.getYq());//string数据转换BigDecimal
  BigDecimal publishPrice =  new BigDecimal(cabinInfo.getPublishPrice());//string数据转换BigDecimal

//进行相加再相乘操作时注意不要直接用符号+、-、*等,后面是四舍五入的格式
  totalPrice =(publishPrice.add(planeTax).add(yq)).multiply( new BigDecimal(model.getBookInfoList().size()))

  .setScale(2,     BigDecimal.ROUND_HALF_UP); 
  totalPrice = price.subtract(couponMoney);

 

你可能感兴趣的:(JavaSE)