Avoiding java floating point arithmetic in groovy by defaulting number type to BigDecimal.

One of the problem while performing addition operation on floating number in java is that it’s results are unexpected. E.g.

class CountingIssue{
   public static void main(String[]  args){

    double sum = 0.0d;
	  for(int i =0;i<10;i++){
          
          sum+=0.1d;
	  }
	  System.out.println(sum); //0.9999999999999999
   }
   
}

As you might be expecting result as 1.0 but the actual output is 0.9999999999. This can lead to big problem for huge numbers.

So it’s recommented to avoid float and decimal if exact answer is required, instead use BigDecimal.

Groovy defaults floating number type to BigDecimal to avoid such problem.

def sum = 0
def number = 0.1 // is used just to show the default data type of floating number
println number.getClass() // class java.math.BigDecimal
10.times{ sum += 0.1} 
println sum // 1.0