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