Working with Money

Figure 524. Limited float precision Slide presentation
final float result = 0.99f - 0.1f -0.1f -0.1f;
System.out.println(result);
0.68999994

Figure 525. Limited double precision Slide presentation
final double result = 0.99 - 0.1 -0.1 -0.1;
System.out.println(result);
0.6900000000000001

Figure 526. Using BigDecimal Slide presentation
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

Figure 527. Chaining BigDecimal operations Slide presentation
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

exercise No. 183

Chaining subtract method calls

Q:

Explain the chaining mechanism implementing three successive subtractions in Figure 527, “Chaining BigDecimal operations ”.

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 subtract(...) call returns a new result instance of class BigDecimal. We can thus chain a subsequent subtract(...) call using this returned instance.

Figure 528. BigDecimal features Slide presentation
  • Higher memory allocation hosting higher precision.

  • Immutable instances

  • Calculation performance penalty.

  • Clumsy interface.