8

我的应用程序正在产生双打,其中 Double.toString() 产生“-3.1999999999999953” - 而我希望它产生“-3.2”。

我实际上是从 JScience 的Amount#getEstimatedValue().

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

如何在没有这个问题的情况下将 Doubles 转换为 Strings?

4

3 回答 3

7

推荐解决方案

BigDecimal.valueOf (hisDouble).toPlainString ()

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

然后一个朋友问我在做什么,并说OP更好用BigDecimal,我进入了掌上模式..

但是我会在这篇文章中留下黑客攻击,以便世界可以看到我有时是多么愚蠢。


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

下面的代码段会将 的值四舍五入yourDecimal到小数点后,然后打印该值。

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

输出

-3.2

有史以来最愚蠢的黑客攻击

  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
于 2011-12-15T17:23:32.000 回答
4

使用BigDecimal

System.out.println(BigDecimal.valueOf(-3.2d).toPlainString());

输出:

-3.2
于 2011-12-15T17:26:55.817 回答
3

你可以试试

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

有点“重量级”,但应该做的伎俩。一些示例用法:

DecimalFormat 子模式边界无法正常工作

于 2011-12-15T17:23:21.143 回答