【问题标题】:Formatting A Double In A String Without Scientific Notation在没有科学记数法的情况下格式化字符串中的双精度数
【发布时间】:2020-10-01 18:55:51
【问题描述】:

我有一个双人间。 double foo = 123456789.1234;。我想把foo 变成一个字符串。 String str = foo+"";。但现在foo 等于“1.234567891234E8”。有没有办法可以在没有科学记数法的情况下将foo 转换为字符串? 我试过了

String str = String.format("%.0f", foo);

但这只是删除了小数。它将str 设置为“123456789”; 我试过了

String str = (new BigDecimal(foo))+"";

但这会失去准确性。其将str 设置为“123456789.1234000027179718017578125”;

【问题讨论】:

  • 仅供参考,BigDecimal 方法不会丢失准确性 - 它准确地描述了存储在 double 中的 实际 值。

标签: java string formatting double bigdecimal


【解决方案1】:

只使用%f 而不是%.0f

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        double foo = 123456789.1234;
        String str = String.format("%f", foo);
        System.out.println(str);

        // If you want to get rid of the trailing zeros
        str = new BigDecimal(str).stripTrailingZeros().toString();
        System.out.println(str);
    }
}

输出:

123456789.123400
123456789.1234

【讨论】:

  • 用于删除尾随零。使用 Big Decimal 是否会导致我应该关注的性能下降?
  • 不...我不知道...它自 Java-5 以来就一直存在(今天我们有 Java-15),我从未听说过/读过它导致任何性能drop...但是,如果有任何疑问,您可以随时进行基准测试。
猜你喜欢
  • 2017-12-24
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2013-04-12
相关资源
最近更新 更多