How to display numbers in scientific notation in Java?


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

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements