Java 中 float 或者double 类型比较大小的正确方式

一、基于阈值的比较

(1)设置一个精度e,

(2)两数相减的结果取绝对值dif

(3)如果dif<e,两数相等,否则不等

 1 private static void thresholdBasedFloatsComparison()
 2 {
 3     final double THRESHOLD = .0001;
 4  
 5     //Method 1
 6     double f1 = .0;
 7     for (int i = 1; i <= 11; i++) {
 8         f1 += .1;
 9     }
10  
11     //Method 2
12     double f2 = .1 * 11;
13  
14     System.out.println("f1 = " + f1);
15     System.out.println("f2 = " + f2);
16  
17     if (Math.abs(f1 - f2) < THRESHOLD)
18         System.out.println("f1 and f2 are equal using threshold\n");
19     else
20         System.out.println("f1 and f2 are not equal using threshold\n");
21 }

 

二、使用BigDecimal

注意:equals  会比较两数的精度

1 private static void testBdEquality(){
2      BigDecimal a = new BigDecimal("2.00");
3      BigDecimal b = new BigDecimal("2.0");
4  
5      System.out.println(a.equals(b));           // false
6  
7      System.out.println(a.compareTo(b) == 0);   // true
8 }

例子:

 1 private static void bigDecimalComparison() {
 2     //Method 1
 3     BigDecimal f1 = new BigDecimal("0.0");
 4     BigDecimal pointOne = new BigDecimal("0.1");
 5     for (int i = 1; i <= 11; i++) {
 6         f1 = f1.add(pointOne);
 7     }
 8  
 9     //Method 2
10     BigDecimal f2 = new BigDecimal("0.1");
11     BigDecimal eleven = new BigDecimal("11");
12     f2 = f2.multiply(eleven);
13  
14     System.out.println("f1 = " + f1);
15     System.out.println("f2 = " + f2);
16  
17     if (f1.compareTo(f2) == 0)
18         System.out.println("f1 and f2 are equal using BigDecimal\n");
19     else
20         System.out.println("f1 and f2 are not equal using BigDecimal\n");
21 }

 

 

posted @ 2019-03-13 20:17  chsobin  阅读(17046)  评论(0编辑  收藏  举报