Java Reference
In-Depth Information
}
public static double recalculate(double fundAmount, double rate){
return fundAmount*(1+rate);
}
}
precision rounding: Bigdecimal vs. douBle
You've seen in this small example that the way doubles are rounded makes them
inaccurate, especially when representing important decimal values, such as money.
There are other classes that will not result in these rounding errors and should be
used in real applications. BigDecimal would be a much better choice because it
offers the developer complete control over how values are rounded. BigDecimal
allows you to specify a scale, or a number of digits after the decimal point, and the
rounding method to use to accomplish this scaling. To illustrate this, have a look
at the same program written with BigDecimal instead of doubles. Remember how
you needed to specify a decimal format to display your double value nicely. With
BigDecimal , you can control the rounding at each calculation, so not only is it dis-
played nicely, but the actual value matches the nice string representation as well.
import java.math.BigDecimal;
public class Errors {
public static void main(String[] args) {
int age = 30;
BigDecimal retirementFund = new BigDecimal("10000.00");
// set the scale to 2 decimal points
// and the rounding to round up when the next digit is >= 5
retirementFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = "David Johnson";
for (int i = age; i <= 65; i++){
retirementFund = recalculate (retirementFund,new
BigDecimal("0.10"));
}
BigDecimal monthlyPension = retirementFund.divide(
yearsInRetirement.multiply(new BigDecimal("12")));
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
public static BigDecimal recalculate(BigDecimal fundAmount,
BigDecimal rate){
// use BigDecimal methods for arithmetic operations
return fundAmount.multiply(rate.add(new
BigDecimal("1.00")));
}
}
continues
 
Search WWH ::




Custom Search