Monday, June 8, 2009

Using java.math.BigDecimal

BigDecimal is a wrapper class over double data type. As Java is having Double wrapper class but still we need to use BigDecimal when precision comparison and other mathematical operation on Double objects (not native data type is required)

BigDecimal is required when the value of double datatype need to be passed in Object form (not in native form). This requirement comes when you do some file operation or you need to pass data over network or distributed application. We can use java.lang.Doublealso when we don’t need to change or manipulate the data contained in Object. But when there are operations like Comparison, addition, multiplication and maintaining precision then I will recommend BigDecimal in place of Double.

BigDecimal contains methods to add, subtract, multiply, divide and compare BigDecimal objects (Java doc link: The methods internally maintain the precisions and Rounding of Parameters which are already present in the Object.

Double (Java doc link: not having such kind of methods and does not maintain precision when you convertDouble wrapper object todouble native value for mathematical operation. Double is having methods to convert double value to String and object value to double and int.

Similarities:Both Doubleand BigDecimal are immutable, i.e. if you do any operation on these objects it does not apply on them unless and until you reassign the new value in them. For example if you want to setScale in a BigDecimal, it won’t get reflected if you don’t reassign the value in old reference.

BigDecimal bd = new BigDecimal(0);

bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);

The statement above will not change the object and it will hold the old precision. To get the effect of the method above try this

bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);

One more thing I would like to add regarding the uniform usability of BigDecimal across the application.

Store the parameters of setScale method in some property or constant and use those property while setting the precision or scale. This will maintain the uniform values and precision of BigDecimal across the application.

For Example instead of statement above use the following coding style:

final static int BIG_DECIMAL_PRECISION_2 = 2;


BigDecimal bd = new BigDecimal(0);


No comments:

Post a Comment

Amazon Best Sellors

Weblogic - Server Creation - Issues

Datasource creation using python script.  Python Script was failing after creating Datasource. From UI Admin Console, if I try to activat...