在Apache的百科全书对于round来源是这样的:为什么我们需要将double转换为字符串,然后才能将其转换为BigDecimal?
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;
}
}
}
我想知道,在创建BigDecimal
时,为什么他们选择(使用Double.toString
),而不是简单地使用双待双转换为字符串本身?
换句话说,这有什么问题? :
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;
}
}
}
@@致谢谢谢! – Pacerier