Calculations are done using BigDecimal only for numbers that are defined as decimal or fixed point literals. If double values are (unwittingly) introduced into decimal expressions, then this could defeat the user’s intent of coding decimal. This is not unlike the behavior of other programming languages such as C, C++, or Java, which automatically “promote” a numeric expression to use the “widest” type to hold the results of numeric calculations. If users want decimal calculations to be done to produce an exact decimal result, then DECIMAL types should be consistently used in the expression.
For example:
procedure pay_check ( decimal(9,2) salary, decimal(9,2) bonus )
returns decimal(9,2);
declare decimal(9,2) total = 0.0;
declare double commission = 10.1;
total = salary + bonus + salary*commission;
return total;
end;
This example assumes that the user wants an exact result. However, the value for commission has incorrectly been defined as double, when decimal should be used, so that any imprecision occurring when storing the value 10.1 into “commission” will be carried into the calculation for “total” where it is later used. The following variation could also create unintended results:
declare decimal(9,2) commission = 10.1F;
Even though the variable is defined as DECIMAL, the fact that the literal is defined as a floating point constant will effectively “promote” the variable to double.
The advantages of BigDecimal include support for arbitrary precision numbers with a high precision and scale. The exactness expected of fixed point arithmetic is guaranteed with this class, and so it is ideally suited for expressions used in financial or similar applications.