public BigDecimal(double val) //将double表示形式转换为BigDecimal public BigDecimal(int val) //将int表示形式转换成BigDecimal public BigDecimal(String val) //将String表示形式转换成BigDecimal
第一种double类型转换不建议使用,原因如下:
1 2 3 4 5 6 7
BigDecimal bigDecimal = new BigDecimal(2); BigDecimal bDouble = new BigDecimal(2.3); BigDecimal bString = new BigDecimal("2.3");
public BigDecimal add(BigDecimal value); //加法 public BigDecimal subtract(BigDecimal value); //减法 public BigDecimal multiply(BigDecimal value); //乘法 public BigDecimal divide(BigDecimal value); //除法
代码如下:
1 2 3 4 5 6 7
BigDecimal a = new BigDecimal("4.5"); BigDecimal b = new BigDecimal("1.5");
System.out.println("a + b =" + a.add(b)); System.out.println("a - b =" + a.subtract(b)); System.out.println("a * b =" + a.multiply(b)); System.out.println("a / b =" + a.divide(b));
运行结果如下:
1 2 3 4
a + b =6.0 a - b =3.0 a * b =6.75 a / b =3
4. BigDecimal保留小数
方法如下:
1 2 3
public BigDecimal setScale(int newScale) public BigDecimal setScale(int newScale, int roundingMode) public BigDecimal setScale(int newScale, RoundingMode roundingMode)//同上
Exception in thread "main" java.lang.ArithmeticException: Rounding necessary at java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4148) at java.math.BigDecimal.needIncrement(BigDecimal.java:4204) at java.math.BigDecimal.divideAndRound(BigDecimal.java:4112) at java.math.BigDecimal.setScale(BigDecimal.java:2452) at java.math.BigDecimal.setScale(BigDecimal.java:2512) at com.hj.demo.test.Test01.main(Test01.java:8)
需要加上第二个参数:
1 2 3
BigDecimal a = new BigDecimal("1.2222"); System.out.println(a.setScale(2,BigDecimal.ROUND_HALF_UP));
运行结果如下:
1
1.22
2. BigDecimal做除法时如果出现除不尽(循环小数)时汇报异常:
1 2 3 4
BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("3"); System.out.println("a / b =" + a.divide(b));
异常如下:
1 2 3
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(BigDecimal.java:1690) at com.hj.demo.test.Test01.main(Test01.java:10)
此时应该给予divide第二个和第三个参数用来保留小数位数:
1 2 3 4
BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("3"); System.out.println("a / b =" + a.divide(b,2,BigDecimal.ROUND_HALF_UP));