Sunday, March 22, 2015

In Java 0 is not always equal to 0

I am a big fan, of the Java BigDecimal class for arithmetic operations. It provides fast and easy to use methods to do calculations in arbitrary precision. But last week i have got a bug report that in one of my programs a check whether a BigDecimal variable is 0 returns a wrong result. Here is the code:


if(value.equals(BigDecimal.ZERO))
 System.out.println("Value is zero");
else
 System.out.println("Value is not zero");


The check for a zero value has always worked, but suddenly last week it stopped working and after some investigation i have found out, that it stops working, because the scale of the value has changed from zero, to two. When you have a look in the java doc of the equals method you see, that this works as designed.

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.

As a workaround for this problem you can replace all your equals method to compareTo which only compares the value and not the scale of the BigDecimal object. 

if(value.compareTo(BigDecimal.ZERO)==0)
 System.out.println("Value is zero");
else
 System.out.println("Value is not zero");

No comments:

Post a Comment

ad