首页 > 代码库 > float,double等精度丢失问题

float,double等精度丢失问题

问题提出:

  12.0f-11.9f = 0.10000038,"减不尽"为什么?

  8888.88*100 = 888887.9999999999   ???

来自MSDN的解释:http://msdn.microsoft.com/zh-cn/c151dt3s.aspx

原因分析:http://www.cnblogs.com/yewsky/articles/1864934.html

解决方法:

技术分享
 1 package t;
 2 
 3 import java.math.BigDecimal;
 4 
 5 public class T {
 6     public static void main(String[] args) {
 7         double a = 8888.88;
 8         int b = 100;
 9         System.out.println(mul(a, b));
10         System.out.println(a * b);
11         System.out.println(sub(12.0, 11.9));
12         System.out.println(12.0 - 11.9);
13     }
14 
15     /**
16      * 加法运算
17      * 
18      * @param num1
19      * @param num2
20      * @return
21      */
22     public static double add(double num1, double num2) {
23         BigDecimal p1 = new BigDecimal(Double.toString(num1));
24         BigDecimal p2 = new BigDecimal(Double.toString(num2));
25         return p1.add(p2).doubleValue();
26     }
27 
28     /**
29      * 减法运算
30      * 
31      * @param num1
32      * @param num2
33      * @return
34      */
35     public static double sub(double num1, double num2) {
36         BigDecimal p1 = new BigDecimal(Double.toString(num1));
37         BigDecimal p2 = new BigDecimal(Double.toString(num2));
38         return p1.subtract(p2).doubleValue();
39     }
40 
41     /**
42      * 乘法运算
43      * 
44      * @param num1
45      * @param num2
46      * @return
47      */
48     public static double mul(double num1, double num2) {
49         BigDecimal p1 = new BigDecimal(Double.toString(num1));
50         BigDecimal p2 = new BigDecimal(Double.toString(num2));
51         return p1.multiply(p2).doubleValue();
52     }
53 
54     /**
55      * 除法运算
56      * 
57      * @param num1
58      * @param num2
59      * @param scale
60      *            小数位数
61      * @return
62      */
63     public static double div(double num1, double num2, int scale) {
64         if (scale < 0) {
65             throw new IllegalArgumentException("Parameter error");
66         }
67         BigDecimal p1 = new BigDecimal(Double.toString(num1));
68         BigDecimal p2 = new BigDecimal(Double.toString(num2));
69         return p1.divide(p2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
70     }
71 }
View Code

 

float,double等精度丢失问题