When to use Bigdecimal
Let's explore this problem with the help of an example:
All floating point values that can represent a currency amount (in dollars and cents) cannot be stored exactly as it is in the memory. So, if we want to store 0.1 dollars (10 cents), float/double can not store it as it is. Instead, the binary can store only a closer approximation value (0.100000001490116119384765625 in decimal). The magnitude of this problem becomes significant (known as loss of significance) when we repetitively do arithmetic operations (multiply or divide) using these two data types. Below, we will demonstrate what this may look like.
Here is an example of the loss of precision using double:
public class DoubleForCurrency {
public static void main(String[] args) {
double total = 0.2;
for (int i = 0; i < 100; i++) {
total += 0.2;
}
System.out.println("total = " + total);
}
}
total = 20.19999999999996
Special Notes
Primitive type: int and long are also useful for monetary calculations if the decimal precision is not required.
We should really avoid using the BigDecimal (double value) constructor, and instead, we should really prefer using the BigDecimal(String), because BigDecimal (0.1) results in (0.1000000000000000055511151231257827021181583404541015625) being stored in the BigDecimal instance. In contrast, BigDecimal ("0.1") stores exactly 0.1.
Comments
Post a Comment