Monday, 28 September 2015

Double alternatives for precise arithmetic

We sure have used double data type in our programming while performing simple or complex arithmetic calculations. Doubles tend to be good enough for most applications (not involving money of course), because if you are dealing with money, you need exact precision. 

Consider this:
double first = 2.00; 
double second = 1.10; 
System.out.println(first - second);
The result?
0.8999999999999999
The problem comes when double suffers from a "loss of precision" and becomes very noticeable when working with either very big numbers or very small numbers. You may be tempted to use print formatting to set the precision in terms of decimal placings, but that still do not solve the root issue.

Especially for monetary-critical applications, (i) you may want to consider using BigDecimal as it is an exact way of representing numbers. With BigDecimal this would not happen. (ii) use int or long to represent cents.

1. Using BigDecimal

Example
BigDecimal first = new BigDecimal("2.00"); 
BigDecimal second = new BigDecimal("1.10"); 
System.out.println(first.subtract(second));
Returns 
0.90
When using BigDecimal, note that it'll take up more memory, creates more garbage and is probably slower for most operations, as compared to using primitive types.


2. Using int or long

Example
System.out.println((200 - 110) + " cents");
Returns
90 cents 
In summary, avoid floating point calculations (e.g. float, double) when working with monetary or precision-critical applications. Consider greatly the use of int, long or BigDecimal instead.

No comments:

Post a Comment