BigDecimal equals() 与 CompareTo()
考虑简单的测试类:
import java.math.BigDecimal;
/**
* @author The Elite Gentleman
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BigDecimal x = new BigDecimal("1");
BigDecimal y = new BigDecimal("1.00");
System.out.println(x.equals(y));
System.out.println(x.compareTo(y) == 0 ? "true": "false");
}
}
您可以(有意识地)说x
等于y
(不是对象引用),但是当您运行程序时,会显示以下结果:
false
true
问题:BigDecimal
中的compareTo()
和equals()
有什么区别,compareTo
可以判断>x
等于是吗?
PS:我看到 BigDecimal 在 equals()
方法上有一个 inflate()
方法。 inflate()
实际上做了什么?
Consider the simple test class:
import java.math.BigDecimal;
/**
* @author The Elite Gentleman
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BigDecimal x = new BigDecimal("1");
BigDecimal y = new BigDecimal("1.00");
System.out.println(x.equals(y));
System.out.println(x.compareTo(y) == 0 ? "true": "false");
}
}
You can (consciously) say that x
is equal to y
(not object reference), but when you run the program, the following result shows:
false
true
Question: What's the difference between compareTo()
and equals()
in BigDecimal
that compareTo
can determine that x
is equal to y
?
PS: I see that BigDecimal has an inflate()
method on equals()
method. What does inflate()
do actually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案在
equals()
方法的 JavaDoc:换句话说:
equals()
检查BigDecimal
对象在每个方面是否完全相同。compareTo()
“仅”比较它们的数值。至于为什么
equals()
的行为方式如此,这已经得到解答在此问题中。The answer is in the JavaDoc of the
equals()
method:In other words:
equals()
checks if theBigDecimal
objects are exactly the same in every aspect.compareTo()
"only" compares their numeric value.As to why
equals()
behaves this way, this has been answered in this SO question.我相信正确的答案是使两个数字(BigDecimals)具有相同的比例,然后我们可以决定它们的相等性。例如,这两个数相等吗?
嗯,这取决于规模。在 5 级(5 个小数点)上,不,它们不一样。但在较小的十进制精度(小数位数 4 及更低)上,它们被认为是相等的。
所以我建议让两个数字的比例相等然后进行比较。
I believe that the correct answer would be to make the two numbers (BigDecimals), have the same scale, then we can decide about their equality. For example, are these two numbers equal?
Well, it depends on the scale. On the scale 5 (5 decimal points), no they are not the same. but on smaller decimal precisions (scale 4 and lower) they are considered equal.
So I suggest make the scale of the two numbers equal and then compare them.
基本上,如果需要的话,
inflate()
会调用BigInteger.valueOf(intCompact)
,即它创建未缩放的值,该值存储为BigInteger
代码>long intCompact。如果您不需要 BigInteger 并且未缩放的值适合 long ,则 BigDecimal 似乎会尝试尽可能节省空间。Basically,
inflate()
callsBigInteger.valueOf(intCompact)
if necessary, i.e. it creates the unscaled value that is stored as aBigInteger
fromlong intCompact
. If you don't need thatBigInteger
and the unscaled value fits into along
BigDecimal
seems to try to save space as long as possible.您还可以与双值进行比较
You can also compare with double value