gpt4 book ai didi

java - RoundingMode.HALF_UP 中的不同结果

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:42 25 4
gpt4 key购买 nike

请随意评论我。下面的程序出了什么问题。它给出了不同的回合结果。

public class Test {
public static String round(double value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}

public static void main(String[] args) throws Exception {
double value1 = 1.1234565;
System.out.println(round(value1, 6));
double value2 = 1.1235;
System.out.println(round(value2, 3));
}
}

为什么会这样?

1.123457
1.123 --> Actually, I expect 1.124

在文档中( eclipse )

enter image description here

最佳答案

您正在调用 BigDecimal(double) 构造函数。记录为:

Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.

笔记也很有启发性,我建议你阅读它们。

您传递的值恰好是 1.12349999999999994315658113919198513031005859375,因为它是最接近 1.1235 的 double。你可以看到,如果你在调用 setScale 之前打印出 bd.toPlainString()。因此,不是在 1.123 和 1.124 之间的中间位置 - 它最接近 1.123。

如果您想要正好 1.1235 的BigDecimal 值,我建议您将其作为String 传递:

import java.math.*;

public class Test {
public static String round(String value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}

public static void main(String[] args) throws Exception {
String value1 = "1.1234565";
System.out.println(round(value1, 6));
String value2 = "1.1235";
System.out.println(round(value2, 3));
}
}

或者,您可以使用 BigDecimal.valueOf(double) 而不是 new BigDecimal(double) - 但是您仍然遇到问题,您已经转换了您的 真正的原始源数据(源代码中的文本)首先转换为二进制 float ,可能会丢失信息。

关于java - RoundingMode.HALF_UP 中的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33889338/

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