Today, when writing a script, we found that the subtraction of the double type has an error with the actual result, such as: 19.9-9.9=9.9999999999999, instead of 10, after Baidu found that double subtraction will be converted to binary, because double valid digits are 16 bit This will result in a situation where the number of decimal places is not enough, in which case there will be error, the solution is to use BigDecimal, its effective length is long enough to store decimal digits so it can be used instead of double to subtraction, the following is the use of BigDecimal:
Serial number |
Method |
Type |
Description |
1 |
Public BigDecimal (double val) |
Structure |
Converts a double representation For BigDecimal |
2 |
Public BigDecimal (int val) |
Structure |
Converts an int representation to a BigDecimal |
3 |
Public BigDecimal (String val) |
Structure |
Represents a String Form conversion to BigDecimal |
4 |
Public BigDecimal Add (BigDecimal augend) |
Ordinary |
Addition |
5 |
Public BigDecimal Subtract (BigDecimal subtrahend) |
Ordinary |
Subtraction |
6 |
Public BigDecimal Multiply (BigDecimal Multiplicand) |
Ordinary |
Multiplication |
7 |
Public BigDecimal Divide (BigDecimal Divisor |
Ordinary |
Division |
Add two double numbers
public static double Add (Double v1,double v2) {
BigDecimal B1 = new BigDecimal (v1.tostring ());
BigDecimal b2 = new BigDecimal (v2.tostring ());
Return B1.add (B2). Doublevalue ();
}
Subtract two double numbers
public static double sub (double v1,double v2) {
BigDecimal B1 = new BigDecimal (v1.tostring ());
BigDecimal b2 = new BigDecimal (v2.tostring ());
Return B1.subtract (B2). Doublevalue ();
}
Multiply two double numbers
public static double Mul (Double v1,double v2) {
BigDecimal B1 = new BigDecimal (v1.tostring ());
BigDecimal b2 = new BigDecimal (v2.tostring ());
Return b1.multiply (B2). Doublevalue ();
}
Divide two double numbers
public static double div (Double v1,double v2) {
BigDecimal B1 = new BigDecimal (v1.tostring ());
BigDecimal b2 = new BigDecimal (v2.tostring ());
Return B1.divide (B2,DEF_DIV_SCALE,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ();
}
Divides two double numbers and preserves scale decimal places
public static double div (double v1,double v2,int scale) {
if (scale<0) {
throw New IllegalArgumentException (
"The scale must be a positive integer or zero");
}
BigDecimal B1 = new BigDecimal (v1.tostring ());
BigDecimal b2 = new BigDecimal (v2.tostring ());
Return B1.divide (B2,SCALE,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ();
}
To rounding
BigDecimal B1 = new BigDecimal (d);
BigDecimal b2 = new BigDecimal (1);
Any number divided by 1 is the original number.
ROUND_HALF_UP is a constant of BigDecimal,
Represents an operation that is rounded
Return B1.divide (B2, Len,bigdecimal.
ROUND_HALF_UP). Doublevalue ();
}
More about BigDecimal usage See: http://www.apihome.cn/api/java/BigDecimal.html