java float and等于0,在Java中使用等于零的运算符(BigDecimal / Double)

本文讨论了0与0.0在equals方法中的不同行为,包括Double和BigDecimal的比较。重点在于类型转换和equals方法的底层实现,建议使用compareTo进行精确值比较。同时揭示了字符串比较在这些情况下的作用。
摘要由CSDN通过智能技术生成

A few interesting observations w.r.t equals operator on 0 and 0.0

new Double(0.0).equals(0) returns false, while new Double(0.0).equals(0.0) returns true.

BigDecimal.ZERO.equals(BigDecimal.valueOf(0.0)) returns false, while BigDecimal.ZERO.equals(BigDecimal.valueOf(0)) returns true.

Looks like the string comparison is being done in both the cases. Could anyone throw some light on this.

Thanks.

解决方案

BigDecimal 'equals' compares the value and the scale. If you only want to compare values (0 == 0.0) you should use compareTo:

BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0.0)) == 0 //true

BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0)) == 0 //true

See the javadoc.

As for the Double comparison, as explained by other answers, you are comparing a Double with an Integer in new Double(0.0).equals(0), which returns false because the objects have different types. For reference, the code for the equals method in JDK 7 is:

public boolean equals(Object obj) {

return (obj instanceof Double)

&& (doubleToLongBits(((Double)obj).value) ==

doubleToLongBits(value));

}

In your case, (obj instanceof Double) is false.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值