Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing BigDecimal

Tags:

java

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.

like image 347
Andrew Valevskiy Avatar asked Dec 19 '22 01:12

Andrew Valevskiy


2 Answers

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 :

BigDecimal.equals(Object)

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).

BigDecimal.compareTo(BigDecimal)

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
like image 77
AxelH Avatar answered Jan 04 '23 16:01

AxelH


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

like image 36
Pierpaolo Di Dato Avatar answered Jan 04 '23 16:01

Pierpaolo Di Dato