BigDecimal:构造器和equal比较

BigDecimal a = new BigDecimal(0.2d);
BigDecimal b = new BigDecimal(String.valueOf(0.2d));
BigDecimal c = new BigDecimal("0.2");
BigDecimal d = new BigDecimal("0.20");
BigDecimal e = BigDecimal.valueOf(0.2d);
System.out.println("a:"+a);
System.out.println("b:"+b);
System.out.println("c:"+c);
System.out.println("d:"+d);
System.out.println("e:"+e);

输出:

a:0.200000000000000011102230246251565404236316680908203125
b:0.2
c:0.2
d:0.20
e:0.2

如你所见,使用BigDecimal(double val)构造方法所产生的结果是不可预测的。
double转换为BigDecimal推荐使用new BigDecimal(String.valueOf(0.2d));或:BigDecimal.valueOf(0.2d);,即采用double->String->BigDecimal的方式。

System.out.println(a.equals(b)); //false
System.out.println(a.equals(c)); //false
System.out.println(a.equals(d)); //false
System.out.println(b.equals(c)); //true
System.out.println(b.equals(d)); //false
System.out.println(c.equals(d)); //false

equals()方法比较两个BigDecimal对象,只有当其值(value)及规模(scale)完全一样时,才为true。因此在这种情况下,2.0!=2.00;

System.out.println(a.compareTo(b)); //1
System.out.println(a.compareTo(c)); //1
System.out.println(a.compareTo(d)); //1
System.out.println(b.compareTo(c)); //0
System.out.println(b.compareTo(d)); //0
System.out.println(c.compareTo(d)); //0

compareTo()方法和自然的比较一致,值(value)相等就相等。

参考:Arbitrary Precision Numbers

你可能感兴趣的:(java)