Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0E30 is not ZERO

I dont know how to handle new BigDecimal("0E30"). Its value is 0 but it doesn't compare to BigDecimal.ZERO. See below:

System.out.println(new BigDecimal("0E30").add(BigDecimal.ONE));     // ---> 1
System.out.println(new BigDecimal("0E30").equals(BigDecimal.ZERO)); // ---> false

Could someone help me to make the comparison true (I know I can get a workaround by converting the BigDecimals to double, but I would like to know what is going on)? I am using JRE 1.6.3. thanks

like image 648
S4M Avatar asked Jan 06 '12 18:01

S4M


2 Answers

From the docs (emphasis is mine):

Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimals 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 this case, the scale doesn't match. So instead, you should use compareTo().

BigDecimal is one of the cases where equals() is inconsistent with compareTo():

Note: care should be exercised if BigDecimals are to be used as keys in a SortedMap or elements in a SortedSet, as BigDecimal's natural ordering is inconsistent with equals. See Comparable, SortedMap or SortedSet for more information.

like image 108
Mysticial Avatar answered Nov 19 '22 20:11

Mysticial


From the docs:

public boolean equals(Object x)

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

Your scales are different. If you want them to compare equal, use compareTo.

like image 43
Kevin Avatar answered Nov 19 '22 19:11

Kevin