最近项目里面用bigdecimal来进行计算,写下这个笔记,直接上代
比较函数 a.compareTo(b) 结果如下:
小于:-1
等于:0
大于:1
@Test
public voidtestBigDeciaml(){
//两个数进行比较
BigDecimal t1 =newBigDecimal(12);
BigDecimal t2 =newBigDecimal(34);
System.out.println("小于"+t1.compareTo(t2));
BigDecimal t3 =newBigDecimal(34);
BigDecimal t4 =newBigDecimal(34);
System.out.println("等于"+t3.compareTo(t4));
BigDecimal t5 =newBigDecimal(56);
BigDecimal t6 =newBigDecimal(34);
System.out.println("大于"+t5.compareTo(t6));
//两个数相除除不尽 会抛出异常
BigDecimal t7 =newBigDecimal("2.00");
BigDecimal t8 =newBigDecimal("1.10");
//java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
// System.out.println("除不尽抛出异常:=="+t1.divide(t2));
//抛出异常用一下方法解决
System.out.println("除不尽解决方法:"+t7.divide(t8,0,BigDecimal.ROUND_DOWN));
}
两个数相除
divide(BigDecimal divisor,intscale,introundingMode)
intscale:相除之后结果保留位数
introundingMode:相除之后结果小数时候按什么样式取出结果这个是枚举
ROUND_UP:向上取整
ROUND_DOWN : 向下取模 直接去掉小数后面数据
ROUND_CEILING
ROUND_FLOOR
ROUND_HALF_UP
ROUND_HALF_DOWN
ROUND_HALF_EVEN
ROUND_UNNECESSARY
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. 除不尽原因 可以参考一下
http://blog.csdn.net/niannian_315/article/details/24354251