Are there other getchas like BigDecimal ("1.0"). Equals (new BigDecimal ("1") returns false?

Recently, I came across behavior inside BigDecimal that I did not know about before. I have always used them as an alternative to the double for areas where precision is important. For example, in financial calculations.

However, I recently encountered this fact.

 new BigDecimal("1.0").equals(new BigDecimal("1")) == false 

I must admit that I was surprised by this. I believe this is because the first has a scale of 1, and the second has a scale of 0, but still it seems contrary to intuition. I think the reason I have never come across this before is because we always used the fixed scale of BigDecimals for financial calculations.

Checking the BigDecimal documentation I can see that it says that compareTo() == 0 should be used to check for equality ignoring scale, while equals() compares value and scale.

Are there any other similar errors that I should know about when using BigDecimal with different scales?

+6
source share
3 answers

There is value and scale to BigDecimal. Both must be equal for BigDecimals equal. From java docs.,.

Unlike compareTo, this method considers two BigDecimal objects to be equal only if they are equal in value and scale (thus, 2.0 is not 2.00 when compared with this method).

https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#equals(java.lang.Object)

+3
source

BigDecimal equally checks that the contents of two BigDecimal objects are the same. for example their toString () will be the same. Just like "1,0" and "1" are not equal, not new BigDecimal("1.0").equals(new BigDecimal("1")) , because unscaledValue() and getScale() both different.

The .equals is that although you knew that == would not compare the contents, and you might have been told that .equals is a solution for String , it may not do what you intended for BigDecimal.

For compareTo he needs to work on what is larger or smaller, and since the values ​​are not larger or smaller than they can be equal (but not equal).

+2
source

According to JavaDoc equals() :

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 comparing this method).

So equals() checks if the objects are exactly the same . compareTo() "only" compares their numeric value.

+1
source

Source: https://habr.com/ru/post/985787/


All Articles