Operation method for BigDecimal in Java
- 2020-04-01 03:38:35
- OfStack
This article illustrates the operation of BigDecimal in Java. Share with you for your reference. Specific analysis is as follows:
BigDecimal is used for business calculations because double, float, and float are not precise enough. The BigDecimal object is created as follows:
BigDecimal b = new BigDecimal("12.000001");
System.out.println(b);
The output result is: 12.000001;
BigDecimal can pass in a String and a double when it's created, but it's best to use a String, as you can see from the following code:
BigDecimal b = new BigDecimal("12.000001");
System.out.println(b);
BigDecimal c = new BigDecimal(12.01);
System.out.println(c);
The running result is:
12.000001
12.0099999999999997868371792719699442386627197265625
You can see that the precision is lost when a double is passed in.
Other operations of BigDecimal are as follows:
//Add < br / >
public static BigDecimal add(String num1, String num2) {
BigDecimal bd1 = new BigDecimal(num1);
BigDecimal bd2 = new BigDecimal(num2);
return bd1.add(bd2);
}
//Subtraction < br / >
public static BigDecimal subtract(String num1, String num2) {
BigDecimal bd1 = new BigDecimal(num1);
BigDecimal bd2 = new BigDecimal(num2);
return bd1.subtract(bd2);
}
//Multiplication < br / >
public static BigDecimal multiply(String num1, String num2) {
BigDecimal bd1 = new BigDecimal(num1);
BigDecimal bd2 = new BigDecimal(num2);
return bd1.multiply(bd2);
}
//Division < br / >
public static BigDecimal divide(String num1, String num2, int i) {
BigDecimal bd1 = new BigDecimal(num1);
BigDecimal bd2 = new BigDecimal(num2);
//I is the number of digits to be reserved, and BigDecimal.ROUND_HALF_UP is the rule for rounding
return bd1.divide(bd2, i, BigDecimal.ROUND_HALF_DOWN);
}
Just to emphasize division, the third parameter is whether to round,
ROUND_HALF_DOWN means when 5 does not enter 1, that is, 1.5-> 1;
ROUND_HALF_UP represents 1 in 5, i.e. 1.5-> 2;
But here's the catch:
When we use ROUND_HALF_DOWN
System.out.println(this.divide("67.75", "5",4));
System.out.println(this.divide("67.75", "5",1));
System.out.println("-------");
System.out.println(this.divide("67.751", "5",4));
System.out.println(this.divide("67.751", "5",1));
The operation results are as follows:
13.5500
13.5
-------
13.5502
13.6
I wonder, the second result is supposed to be 13.5! Why 13.6. Later, after many tests, thought for a moment, the round is not in accordance with the precision behind the shift and 5, but according to the precision of a 5, after all of the data and that is: accurate to 13.5500 a, compared with 5, use 0.0500 and accurate to 13.5502 a, compared with 5, use 0.0502 is greater than 5, so I closed up.
I hope this article has been helpful to your Java programming.