The source for round in apache commons looks like this:
public static double round(double x, int scale, int roundingMethod) {
try {
return (new java.math.BigDecimal(Double.toString(x)).setScale(scale, roundingMethod)).doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
I was wondering, when creating the BigDecimal why did they chose to convert the double to a string (using the Double.toString) instead of simply using the double itself?
In other words, what’s wrong with this? :
public static double round(double x, int scale, int roundingMethod) {
try {
return (new java.math.BigDecimal(x).setScale(scale, roundingMethod)).doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
It’s because the result of
BigDecimal(double)constructor is unpredictable as mentioned in javadoc.Test Case: