Problem:
An operation on a value of two double is sometimes a problem with an exception to the result value. Like what:
System.out.println (19.99+20);
System.out.println (1.0-0.66);
System.out.println (0.033*100);
System.out.println (12.3/100);
Output:
39.989999999999995
0.33999999999999997
3.3000000000000003
0.12300000000000001
Workaround:
Simple floating-point types float and double in Java are not capable of operations, because in most cases it is normal, but occasionally the problem shown above appears. This problem is not a Java bug, because the computer itself is binary, and floating-point number is actually only an approximation, so from binary to decimal floating-point numbers, precision is easily lost, resulting in reduced precision.
To ensure the accuracy of using the BigDecimal class, and can not directly from the double to the BigDecimal, you want to turn a double string to BigDecimal. That is, you cannot use the BigDecimal (double Val) method, and you will find no effect. To use the BigDecimal (String val) method. The specific examples are shown below.
Double Type Arithmetic Example:
1, add
public static double Add (double a1, double B1) {
BigDecimal a2 = new BigDecimal (double.tostring (A1));
BigDecimal b2 = new BigDecimal (Double.tostring (B1));
Return A2.add (B2). Doublevalue ();
}
2, subtract
public static Double sub (double A1, double B1) {
BigDecimal a2 = new BigDecimal (double.tostring (A1));
BigDecimal b2 = new BigDecimal (Double.tostring (B1));
Return A2.subtract (B2). Doublevalue ();
}
3, multiply
public static Double Mul (double A1, double B1) {
BigDecimal a2 = new BigDecimal (double.tostring (A1));
BigDecimal b2 = new BigDecimal (Double.tostring (B1));
Return a2.multiply (B2). Doublevalue ();
}
4. Dividing
public static Double div (double A1, double b1, int scale) {
if (Scale < 0) {
throw new illegalargumentexception ("error");
}
BigDecimal A2 = new BigDecimal (double.tostring (A1));
BigDecimal b2 = new BigDecimal (Double.tostring (B1));
Return A2.divide (B2, scale, bigdecimal.round_half_up). Doublevalue ();
Scale the specified precision when the parameter is not endless.
The above this Java double type operation result unusual solution method is small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.