0

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?

gab06
  • 578
  • 6
  • 23
  • 3
    Possible duplicate of http://stackoverflow.com/questions/2944822/format-double-value-in-scientific-notation – resueman Sep 05 '14 at 19:04

3 Answers3

4

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

Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239
1

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

new Objekt
  • 414
  • 3
  • 8
1

Read about DecimalFormat.

    String number = "3.4213946120686956E-9";
    DecimalFormat format = new DecimalFormat("#.##E0");
    System.out.println(format.format(new BigDecimal(number)));
Olayinka
  • 2,813
  • 2
  • 25
  • 43