private static void scalingMethod(double dbl) {
int ix = (int)(dbl * 100.0); // scale it
double dbl2 = ((double)ix)/100.0;
System.out.println("Scaling... dbl=" + dbl + ", dbl2=" + dbl2);
}
Code like this has often been used, but is affected by a rounding error. For example, if the input is 12.3456 then this method will work; but, if the value of 12.3456 approaches 13.00 then the method fails.
Output to scalingMethod()
Scaling... dbl=12.3456, dbl2=12.34
Scaling... dbl=12.7896, dbl2=12.78
The solution to this age old problem is to use Java's inbuilt DecimalFormat class, which will do all the hard work for you.
private static void decimalFormatMethod(double dbl) {
DecimalFormat df = new DecimalFormat("#.##");
double dbl2 = Double.valueOf(df.format(dbl));
System.out.println("DecimalFormat... dbl=" + dbl + ", dbl2=" + dbl2);
}
Output to decimalFormat()
DecimalFormat... dbl=12.3456, dbl2=12.35
DecimalFormat... dbl=12.7896, dbl2=12.79
As you can see, the input has been rounded correctly in both of the above input scenarios.
No comments:
Post a comment