项目中涉及到了BigDecimal的加、减、乘、比较大小、精确度的问题。所以在此总结一下,方便以后复习。
- 1 //加法
- 2
- 3 BigDecimal coins = new BigDecimal("0");
- 4
- 5 BigDecimal one = new BigDecimal("1");
- 6
- 7 BigDecimal two = new BigDecimal("2");
- 8
- 9 coins = coins.add( two ); //coins 加 2
- 10 System.out.println( coins.doubleValue()); //输出为2.0
- 11
- 12 coins = coins.subtract( one ); //coins 减 1
- 13 System.out.println( coins.doubleValue()); //输出为1.0
- 14
- 15 coins = coins.subtract( two ); //coins 乘以 2
- 16 System.out.println( coins.doubleValue()); //输出为2.0
- 17
- 18 int i = coins .compareTo(BigDecimal.ZERO) ; //判断coins是否大于0
- 19 int k = coins .compareTo( one ) ;//如果 i =0 说明相等;i < 0 说明 coins小于 one; i > 0 说明coins > one
- 20 coins = coins.setScale(2,BigDecimal.ROUND_HALF_UP) //保存两位小数点
1,java代码去除BigDecimal多余的零
private BigDecimal vipPrice;String price = vipPrice.stripTrailingZeros().toPlainString();2,Mybaties 查询myslq中decimal时,去除多余的零select 0 + CAST(good.vipPrice AS CHAR) AS vipPricefrom table;