【问题标题】:Java - Format numbers in scientific notationJava - 以科学计数法格式化数字
【发布时间】:2014-09-05 18:57:26
【问题描述】:

我想格式化这个String:

String number = "3.4213946120686956E-9";

到这里:

String number = "3.42E-9";

四舍五入到小数点后两位。我怎样才能实现它?

【问题讨论】:

标签: java double


【解决方案1】:

试试new DecimalFormat("0.##E0")。 Javadoc:DecimalFormat

例子:

public class Test {

  private static java.text.DecimalFormat sf = new java.text.DecimalFormat("0.##E0");

  public static void main(String[] args) {
    System.out.println(sf.format(Double.parseDouble("3.4213946120686956E-9")));
  }
};

输出:3.42E-9

【讨论】:

    【解决方案2】:

    这不是最优雅的解决方案,但您可以:

    EX:字符串编号 = "3.4213946120686956E-9";

    如果字符串中有句点和 E

    按句点分割字符串,得到句点后的前2个字符=42

    获取末尾的最后 3 个字符 = E-9

    然后将它与句点之前的所有字符一起添加回来 = 3 + "." + 42 + E-9

    【讨论】:

    • 很好,但该方法没有四舍五入:)
    【解决方案3】:

    了解DecimalFormat

        String number = "3.4213946120686956E-9";
        DecimalFormat format = new DecimalFormat("#.##E0");
        System.out.println(format.format(new BigDecimal(number)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2013-08-06
      • 2011-02-26
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多