newScale: 保留newScale位小数
roundingMode: 舍去规则(0 <= roundingMode <= 7)
分别有8个常量
ROUND_UP(0):第newScale位小数进1,后面舍去
BigDecimal b1 = new BigDecimal(3.1415926);
BigDecimal b2 = b1.setScale(2, BigDecimal.ROUND_UP);
System.out.println(b2);// 3.15
ROUND_DOWN(1):第newScale位后面的,直接舍去
BigDecimal b1 = new BigDecimal(3.1415926);
BigDecimal b2 = b1.setScale(2, BigDecimal.ROUND_DOWN);
System.out.println(b2);// 3.14
ROUND_CEILING(2):如果是正数,同ROUND_UP,如果是负数,同ROUND_DOWN
BigDecimal b1 = new BigDecimal(3.1415926);
BigDecimal b2 = b1.setScale(2, BigDecimal.ROUND_CEILING);
System.out.println(b2);// 3.15
b1 = new BigDecimal(-3.1415926);
b2 = b1.setScale(2, BigDecimal.ROUND_CEILING);
System.out.println(b2);// -3.14
ROUND_FLOOR(3):与ROUND_CEILING相反
BigDecimal b1 = new BigDecimal(3.1415926);
BigDecimal b2 = b1.setScale(2, BigDecimal.ROUND_FLOOR);
System.out.println(b2);// 3.14
b1 = new BigDecimal(-3.1415926);
b2 = b1.setScale(2, BigDecimal.ROUND_FLOOR);
System.out.println(b2);// -3.15
ROUND_HALF_UP(4):四舍五入:小学学过的那种
BigDecimal b1 = new BigDecimal(3.1415926);
BigDecimal b2 = b1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b2);// 3.14
b1 = new BigDecimal(3.1455926);
b2 = b1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b2);// 3.15
ROUND_HALF_DOWN(5):另一种四舍五入:舍去部分 > 0.5时,表现为ROUND_UP,否则表现为ROUND_DOWN
BigDecimal b1 = new BigDecimal(3.55);
System.out.println(b1);// 3.54999999999999982236431605997495353221893310546875
BigDecimal b2 = b1.setScale(1, BigDecimal.ROUND_HALF_DOWN);
System.out.println(b2);// 3.5
b1 = new BigDecimal(3.551);
System.out.println(b1);// 3.5510000000000001563194018672220408916473388671875
b2 = b1.setScale(1, BigDecimal.ROUND_HALF_DOWN);
System.out.println(b2);// 3.6
ROUND_HALF_EVEN(6):舍去部分左边为奇数:表现为ROUND_HALF_UP;偶数:表现为ROUND_HALF_DOWN
BigDecimal b1 = new BigDecimal(3.55);
System.out.println(b1);// 3.54999999999999982236431605997495353221893310546875
BigDecimal b2 = b1.setScale(1, BigDecimal.ROUND_HALF_EVEN);// 舍去部分从4开始,4是偶数
System.out.println(b2);// 3.5
b1 = new BigDecimal(3.551);
System.out.println(b1);// 3.5510000000000001563194018672220408916473388671875
b2 = b1.setScale(1, BigDecimal.ROUND_HALF_EVEN);
System.out.println(b2);// 3.6
ROUND_UNNECESSARY(7):
Rounding mode to assert that the requested operation has an exactresult, hence no rounding is necessary. If this rounding mode isspecified on an operation that yields an inexact result, an ArithmeticException is thrown.
舍入模式断言请求的操作具有精确结果,因此不需要舍入。 如果在产生不精确结果的操作上指定了此舍入模式,则抛出ArithmeticException。
BigDecimal.abs();返回BigDecimal:绝对值
BigDecimal.negate();返回BigDecimal:相反数