gpt4 book ai didi

java - 为什么我们需要先将 double 转换为字符串,然后才能将其转换为 BigDecimal?

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:59 24 4
gpt4 key购买 nike

round 的来源在 apache commons 中看起来像这样:

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 转换为字符串(使用 Double.toString)而不是简单地使用 double 本身?

换句话说,这有什么问题? :

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;
}
}
}

最佳答案

这是因为 BigDecimal(double) 构造函数的结果如 javadoc 中所述是不可预测的。

One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

测试用例:

System.out.println(java.math.BigDecimal.valueOf(0.1).toString());
System.out.println(new java.math.BigDecimal(0.1).toString());

关于java - 为什么我们需要先将 double 转换为字符串,然后才能将其转换为 BigDecimal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com