BigDecimal的使用
基本计算方法
- 乘 multiply()
- 除 divide()
- 加 add()
- 减 subtract()
保留小数点位数
/*
** 使用BigDecimal这个方法
*@param newScale 小数点位数
* @param roundingMode 舍去方式
* @return
*/
public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
return setScale(newScale, roundingMode.oldMode);
}
/**
* 除法也可以直接在计算是传入参数保留小数点
* @param divisor 除数
* @param scale 小数点位数
* @param roundingMode 舍去方式
* @return
*/
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
return divide(divisor, scale, roundingMode.oldMode);
}
RoundingMode的几个形式
-
HALF_UP 四舍五入,即,值>=0.5,入,否则舍去
-
CEILING 值向上取整,值变大
-
FLOOR 值向下取整,值变小
-
HALF_DOWN 绝对值 >0.5 ,才入,否则舍去。
-
HALF_EVEN ,
- 如果丢弃的分数左边的数字是奇数,则表现与HALF_UP相同;
- 如果是偶数,其行为与HALF_DOWN相同。
-
UP 绝对值向上取整,正数变大,负数变小
-
DOWN 绝对值向下取整,正数变小,负数变大
-
ROUND_UNNECESSARY, 舍入模式断言所请求的操作具有精确的结果,因此不需要舍入。如果在产生不精确结果的操作上指定此舍入模式,则会引发ArithmeticException 。
Result of rounding input to one digit with the given rounding mode | ||||||||
---|---|---|---|---|---|---|---|---|
Input Number | {@code UP} | {@code DOWN} | {@code CEILING} | {@code FLOOR} | {@code HALF_UP} | {@code HALF_DOWN} | {@code HALF_EVEN} | {@code UNNECESSARY} |
5.5 | 6 | 5 | 6 | 5 | 6 | 5 | 6 | throw {@code ArithmeticException} |
2.5 | 3 | 2 | 3 | 2 | 3 | 2 | 2 | throw {@code ArithmeticException} |
1.6 | 2 | 1 | 2 | 1 | 2 | 2 | 2 | throw {@code ArithmeticException} |
1.1 | 2 | 1 | 2 | 1 | 1 | 1 | 1 | throw {@code ArithmeticException} |
1.0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
-1.0 | -1 | -1 | -1 | -1 | -1 | -1 | -1 | -1 |
-1.1 | -2 | -1 | -1 | -2 | -1 | -1 | -1 | throw {@code ArithmeticException} |
-1.6 | -2 | -1 | -1 | -2 | -2 | -2 | -2 | throw {@code ArithmeticException} |
-2.5 | -3 | -2 | -2 | -3 | -3 | -2 | -2 | throw {@code ArithmeticException} |
-5.5 | -6 | -5 | -5 | -6 | -6 | -5 | -6 | throw {@code ArithmeticException} |