Java - Format numbers in scientific notation

岁酱吖の 提交于 2019-12-25 03:53:21

问题


I want to format this String:

String number = "3.4213946120686956E-9";

to this:

String number = "3.42E-9";

Rounding to 2 decimals. How can I achieve it?


回答1:


Try new DecimalFormat("0.##E0"). Javadoc: DecimalFormat

Example:

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")));
  }
};

Output: 3.42E-9




回答2:


This is not the most elegant solution but you could:

EX: String number = "3.4213946120686956E-9";

if the String has a period and an E in it

split the string by the period, and get the first 2 characters after the period = 42

get the last 3 characters at the end = E-9

and then just add it back together with all the characters before the period = 3 + "." + 42 + E-9




回答3:


Read about DecimalFormat.

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


来源:https://stackoverflow.com/questions/25692274/java-format-numbers-in-scientific-notation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!