BigDecimal
is an exact way of storing decimals.
BigDecimal revenue = new BigDecimal("20.99"); BigDecimal cost = new BigDecimal("5.98"); println(revenue.subtract(cost)) Output >> 15.01
double
has a certain precision.
double revenue = 20.99 double cost = 5.98 println(revenue - cost) println(roundMethod(revenue - cost)) Output >> 15.009999999999998 >> 15.01 (after rounding)
Final Remarks
In the bank application, we rounded the double to two decimal places. In real life if you end up working on some sort of payment system you will use BigDecimal
to store currency, not double
. If you feel like challenging yourself, feel free to replace the doubles in our application with BigDecimal
. You can use the following methods to:
Add: decimal.add(augend)
Subtract: decimal.subtract(subtrahend);
Multiply: decimal.multiply(multiplicand);
Divide: decimal.divide(divisor);