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
  • 538
  • 6
  • 22

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
  • 37,290
  • 26
  • 139
  • 220
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
  • 404
  • 2
  • 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,754
  • 1
  • 25
  • 43