BigDecimal存在的判等问题
BigDecimal 可以解决浮点数精确的问题,但是浮点数在判等上又有无法和正常基本路线判等的效果。
基本类型可以使用==进行判等,但是BigDecimal 并非基本类型,判等时一般会使用equals。
System.out.println(1.0==1);
System.out.println(new BigDecimal("1.0").equals(new BigDecimal("1")));
//结果
true
false
1.打开源码查看BigDecimal 的equals方法
/**
* Compares this {@code BigDecimal} with the specified
* {@code Object} for equality. Unlike {@link
* #compareTo(BigDecimal) compareTo}, this method considers two
* {@code BigDecimal} objects equal only if they are equal in
* value and scale (thus 2.0 is not equal to 2.00 when compared by
* this method).
*
* @param x {@code Object} to which this {@code BigDecimal} is
*
to be compared.
* @return {@code true} if and only if the specified {@code Object} is a
*
{@code BigDecimal} whose value and scale are equal to this
*
{@code BigDecimal}'s.
* @see #compareTo(java.math.BigDecimal)
* @see #hashCode
*/
@Override
public boolean equals(Object x)
里面明确的写出 BigDecimal 的 equals比较的是BigDecimal 的 value 和 scale。
查看debug可以知道两者的scale并不相等
2.解决方法 使用 compareTo仅仅进行值比较
System.out.println(new BigDecimal("1.0").compareTo(new BigDecimal("1"))==0);
//结果
true
3.解决:BigDecimal在集合中使用
由于一些集合中的值比较是通过 equals 和 hashCode,存在hashMap等,这样会使得 1.0和1不相等。
3.1解决方案1
TreeSet 替换 HashSet , TreeSet 不适用hashCode,也不适用equals进行比较元素,而是使用compareTo。
3.2解决方案2
在存入一些集合容器中,先进行stripTrailingZeros的方式尾部去零。
Set<BigDecimal> hashSet2 = new HashSet<>();
hashSet2.add(new BigDecimal("1.0").stripTrailingZeros());
System.out.println(hashSet2.contains(new BigDecimal("1.00").stripTrailingZeros()));