BigDecimal num1 = new BigDecimal("3.1415926");
BigDecimal num2 = new BigDecimal("2");
1. Cuatro aritmética
1.1, además
Informacion oficial:
ejemplo:
//1、加法 num1 + num2
// add(BigDecimal augend)
System.out.println(num1.add(num2));
1.2, resta
Informacion oficial:
ejemplo:
//2、减法 num1 - num2
// subtract(BigDecimal subtrahend)
System.out.println(num1.subtract(num2));
1.3, multiplicación
Informacion oficial:
ejemplo:
//3、乘法 num1 * num2
// multiply(BigDecimal multiplicand)
System.out.println(num1.multiply(num2));
1.4, división
Informacion oficial:
ejemplo:
//4、除法 num1 / num2
//divide(BigDecimal divisor)
System.out.println(num1.divide(num2));
2. Lugares decimales
Informacion oficial:
Ejemplo: num1, num2 retienen 3 lugares decimales respectivamente
System.out.println(num2.setScale(3));
System.out.println(num1.setScale(3, RoundingMode.HALF_UP));
Explicación:
Si los datos de tipo BigDecimal contienen decimales, utilice RoundingMode, utilice directamentesetScale(int newScale)这个会报错,不包含小数点的都可以使用
3、关于
RoundingMode, existen los siguientes:
ejemplo:
valor de entrada | ARRIBA | ABAJO | TECHO | SUELO | HALF_UP | HALF_DOWN | HALF_EVEN | INNECESARIO |
5.5 | 6 | 5 | 6 | 5 | 6 | 5 | 6 | lanzar ArithmeticException |
2.5 | 3 | 2 | 3 | 2 | 3 | 2 | 2 | lanzar ArithmeticException |
1,6 | 2 | 1 | 2 | 1 | 2 | 2 | 2 | lanzar ArithmeticException |
1.1 | 2 | 1 | 2 | 1 | 1 | 1 | 1 | lanzar ArithmeticException |
1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
-1 | -1 | -1 | -1 | -1 | -1 | -1 | -1 | -1 |
-1,1 | -2 | -1 | -1 | -2 | -1 | -1 | -1 | lanzar ArithmeticException |
-1,6 | -2 | -1 | -1 | -2 | -2 | -2 | -2 | lanzar ArithmeticException |
-2,5 | -3 | -2 | -2 | -3 | -3 | -2 | -2 | lanzar ArithmeticException |
-5,5 | -6 | -5 | -5 | -6 | -6 | -5 | -6 | lanzar ArithmeticException |