Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is BigDecimal.equals specified to compare both value and scale individually?

This is not a question about how to compare two BigDecimal objects - I know that you can use compareTo instead of equals to do that, since equals is documented as:

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

The question is: why has the equals been specified in this seemingly counter-intuitive manner? That is, why is it important to be able to distinguish between 2.0 and 2.00?

It seems likely that there must be a reason for this, since the Comparable documentation, which specifies the compareTo method, states:

It is strongly recommended (though not required) that natural orderings be consistent with equals

I imagine there must be a good reason for ignoring this recommendation.

like image 210
bacar Avatar asked Dec 31 '12 13:12

bacar


People also ask

How do you know if two BigDecimal values are equal?

BigDecimal. equals() method 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).

How does BigDecimal compare to double in Java?

Convert the double to a BigDecimal, using rounding, and then use compareTo(). Note that equals() takes into account decimal positions, so compareTo() is safer. You may need to round the BigDecimal as well.

What is scale and precision in BigDecimal?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

How does BigDecimal compare to int?

Use the compareTo method of BigDecimal : public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal. Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.


1 Answers

Because in some situations, an indication of precision (i.e. the margin of error) may be important.

For example, if you're storing measurements made by two physical sensors, perhaps one is 10x more precise than the other. It may be important to represent this fact.

like image 189
Oliver Charlesworth Avatar answered Sep 20 '22 15:09

Oliver Charlesworth