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()));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小小狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值