How to display numbers in scientific notation in Java?

Java 8Object Oriented ProgrammingProgramming

To display number in scientific notation, create NumberFormat object first −

NumberFormat numFormat = newDecimalFormat();

Now, let’s say you need to format the minimum value of Integer −

int i = Integer.MIN_VALUE;
System.out.println(i);
numFormat = newDecimalFormat("0.######E0");
System.out.println(numFormat.format(i));
numFormat = newDecimalFormat("0.#####E0");
System.out.println(numFormat.format(i));

Above, we have used format() method of the NumberFormat class.

Example

 Live Demo

import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Demo {
   public static void main(String args[]) {
      NumberFormat numFormat = new DecimalFormat();
      int i = Integer.MIN_VALUE;
      System.out.println(i);
      numFormat = new DecimalFormat("0.######E0");
      System.out.println(numFormat.format(i));
      numFormat = new DecimalFormat("0.#####E0");
      System.out.println(numFormat.format(i));
      double val = 0.37872;
      numFormat = new DecimalFormat("0.#####E0");
      System.out.println(numFormat.format(val));
      numFormat = new DecimalFormat("000000E0");
      System.out.println(numFormat.format(val));
   }
}

Output

-2147483648
-2.147484E9
-2.14748E9
3.7872E-1
378720E-6
raja
Published on 24-Apr-2019 12:20:27
Advertisements