question:
When performing operation on two double types of values, sometimes there will be problems with abnormal result values. for example:
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.989999999999999999995
0.33999999999999999999997
3.300000000000000003
0.123000000000000001
Solution:
Simple floating point types float and double in Java cannot perform operations because it is normal in most cases, but occasionally problems as shown above occur. This problem is actually not a bug in JAVA, because the computer itself is binary, and floating-point numbers are actually just approximate values. Therefore, when converted from binary to decimal floating-point numbers, the accuracy is easily lost, resulting in a decrease in accuracy.
To ensure accuracy, you must use the BigDecimal class, and you cannot directly convert from double to BigDecimal. You must convert double to string and then BigDecimal. That is, you cannot use the BigDecimal(double val) method, and you will find that there is no effect. To use the BigDecimal(String val) method. Specific examples are shown below.
Examples of four operations of double type:
1. Add up
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. Subtraction
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. Decomposition
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(); }When the scale parameter is divided into incomplete, specify the accuracy.
The solution to the abnormal operation result of double type in Java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.