gpt4 book ai didi

java - 如何使 Java 格式成为 -3.2 而不是 -3.1999999999999953 的 double 格式?

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

我的应用正在生成 double ,其中 Double.toString() 生成“-3.1999999999999953”——而我希望它生成“-3.2”。

我实际上是从 JScience 的 Amount#getEstimatedValue() 得到这些 double 的.

我不想为精度设置任意位数,因为我不知道有多少位数是有效的,但我不希望它生成以“99999999.*”结尾的数字。

如何在没有这个问题的情况下将 double 转换为字符串?

最佳答案

推荐方案

BigDecimal.valueOf (hisDouble).toPlainString ()

在尝试解决 OP 问题时,首先想到的是本文最后一部分提供的 hack。

然后一位 friend 问我在做什么,他说 OP 最好使用 BigDecimal 然后我进入了 facepalm 模式..

但我会在这篇文章中留下黑客,让世界看到我有时有多么愚蠢。


打印时可以使用System.out.format

下面的代码片段会将 yourDecimal 的值四舍五入为一位小数,然后打印该值。

Double yourDouble = -3.1999999999999953;
System.out.format ("%.1f", yourDouble);

输出

-3.2

有史以来最愚蠢的 hack

  public static String fixDecimal (Double d) {
String str = "" + d;
int nDot = str.indexOf ('.');

if (nDot == -1)
return str;

for (int i = nDot, j=0, last ='?'; i < str.length (); ++i) {
j = str.charAt (i) == last ? j+1 : 0;

if (j > 3)
return String.format ("%."+(i-nDot-j-1)+"f", d);

last = str.charAt (i);
}

return str;
}

...

Double[] testcases = {
3.19999999999953,
3.145963219488888,
10.4511111112,
100000.0
};

for (int i =0; i < testcases.length; ++i)
System.out.println (
fixDecimal (testcases[i]) + "\n"
);

输出

3.2
3.1459632195
10.45
100000.0

关于java - 如何使 Java 格式成为 -3.2 而不是 -3.1999999999999953 的 double 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8524079/

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