Working with Money
final float result = 0.99f - 0.1f -0.1f -0.1f;
System.out.println(result);
0.68999994
final double result = 0.99 - 0.1 -0.1 -0.1;
System.out.println(result);
0.6900000000000001
BigDecimal
final BigDecimal zero_dot_99 = new BigDecimal("0.99");
final BigDecimal zero_dot_1 = new BigDecimal("0.1");
BigDecimal
result = zero_dot_99.subtract(zero_dot_1); // Subtracting 0.1
result = result.subtract(zero_dot_1); // Subtracting 0.1
result = result.subtract(zero_dot_1); // Subtracting 0.1
System.out.println(result);
0.69
BigDecimal
operations final BigDecimal zero_dot_99 = new BigDecimal("0.99");
final BigDecimal zero_dot_1 = new BigDecimal("0.1");
BigDecimal result = zero_dot_99.
subtract(zero_dot_1).
subtract(zero_dot_1).
subtract(zero_dot_1);
System.out.println(result);
0.69
No. 178
Chaining subtract method calls
Q: |
Explain the chaining mechanism implementing three successive
subtractions in Figure 543, “Chaining |
A: |
We may re-write the statement in question: result = zero_dot_99.subtract(zero_dot_1).subtract(zero_dot_1).subtract(zero_dot_1); \ / / / \ / / / \ / / / 0.99 - 0.1 / / \ / / \ / / \ / / 0.98 - 0.1 / \ / \ / 0.97 - 0.1 == 0.96 Each |
BigDecimal
features -
Higher memory allocation hosting higher precision.
-
Immutable instances
-
Calculation performance penalty.
-
Clumsy interface.