Reputation: 559
I have following two BigDecimal objects.
BigDecimal one = new BigDecimal(3.0);
BigDecimal two = new BigDecimal(3.00);
System.out.println(one.scale());//0
System.out.println(two.scale());//0
System.out.println(one.equals(two));//true
I've read JavaDocs, but anywhere can't understand what is difference between equals
and compareTo
method. JavaDoc says that these objects isn't equal by equals
method and result must be false
, but result is true
. I'm confused.
Upvotes: 9
Views: 27267
Reputation: 14572
You need to use the String
constructor to get the correct scales, because the BigDecimal(double)
will get the small scale possible
translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.
More precision about the documentations :
Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two 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).
Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.
You will find that the equals
use the scale for the comparison, giving some "strange" result.
BigDecimal bd1 = new BigDecimal("2"); //scale 0
BigDecimal bd2 = new BigDecimal("2.00"); //scale 2
bd1.equals(bd2); //false
bd1.compareTo(bd2); //0 => which means equivalent
Upvotes: 13
Reputation:
Change new BigDecimal(3.0);
to new BigDecimal("3.0");
and you will see the difference.
You used the constructor new BigDecimal(double val)
with a double-literal which value is just 3
it doesn't matter if you write 3.0
or 3.0000
.
Also be careful with this constructor since it represents the exact decimal representation of the double's binary floating-point value, therefor new BigDecimal(0.1)
creates a BigDecimal with the value 0.1000000000000000055511151231257827021181583404541015625
(See JavaDoc)
Better (always) use the constructor new BigDecimal(String val)
.
Upvotes: 3
Reputation: 319
It's better to use compareTo for BigDecimal. This method will return a number greater than zero if a > b, 0 if a == b, and less than zero if a < b
Upvotes: 3