Formatting a Number in Exponential Notation


 

Formatting a Number in Exponential Notation

In this section, you will learn how to format a number in Exponential Notation.

In this section, you will learn how to format a number in Exponential Notation.

Formatting a Number in Exponential Notation

In this section, you will learn how to format a number in Exponential Notation.

Java has designed several classes for parsing and formatting the numbers like DecimalFormat class. This class supports different kinds of numbers, including integers, fixed-point numbers, exponential notation , percentages and currency amounts. Here we are going to format a number in exponential notation.

The 'E' specifies that a number should be formatted in exponential notation. It can also separates the mantissa from the exponent. In the given example, we have defined several formats to express the numbers in different exponential notation. The method format() formats the number in exponential notation.

Here is the code:

import java.text.*;

public class FormattingInExponentialNotation {
	public static void main(String[] args) {
		DecimalFormat nf1 = new DecimalFormat("0000E00");
		String f1 = nf1.format(-87654.321);
		System.out.println(f1);
		DecimalFormat nf2 = new DecimalFormat("0000000E0");
		String f2 = nf2.format(-87654.321);
		System.out.println(f2);
		DecimalFormat nf3 = new DecimalFormat("0.0E0");
		String f3 = nf3.format(-87654.321);
		System.out.println(f3);
		DecimalFormat nf4 = new DecimalFormat("00.00E0");
		String f4 = nf4.format(-87654.321);
		System.out.println(f4);
		DecimalFormat nf5 = new DecimalFormat("###E0");
		String f5 = nf5.format(-87654.321);
		System.out.println(f5);
	}
}

Output:

-8765E01
-8765432E-2
-8.8E4
-87.65E3
-87.7E3

Ads