Java - Format numbers in scientific notation

2019-09-19 06:28发布

问题:

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


标签: java double