Java - Format numbers in scientific notation

2019-09-19 06:27发布

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?

标签: java double
3条回答
女痞
2楼-- · 2019-09-19 06:47

Read about DecimalFormat.

    String number = "3.4213946120686956E-9";
    DecimalFormat format = new DecimalFormat("#.##E0");
    System.out.println(format.format(new BigDecimal(number)));
查看更多
Luminary・发光体
3楼-- · 2019-09-19 06:48

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

查看更多
贼婆χ
4楼-- · 2019-09-19 06:49

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

查看更多
登录 后发表回答