BigDecimal equals() versus compareTo()
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 Big开发者_如何学GoDecimal("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?
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
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).
In other words: equals()
checks if the BigDecimal
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.
I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?
Basically, inflate()
calls BigInteger.valueOf(intCompact)
if necessary, i.e. it creates the unscaled value that is stored as a BigInteger
from long intCompact
. If you don't need that BigInteger
and the unscaled value fits into a long
BigDecimal
seems to try to save space as long as possible.
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?
1.00001 and 1.00002
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.
You can also compare with double value
BigDecimal a= new BigDecimal("1.1"); BigDecimal b =new BigDecimal("1.1");
System.out.println(a.doubleValue()==b.doubleValue());
精彩评论