Tuesday, July 13, 2010

Format a Decimal Number Using Scientific Notation in Java

To format a decimal number (double) using scientific notation in Java we can use the java.text.DecimalFormat class. The following code example demonstrates formatting the number of decimal digits and the number exponent digits of a decimal number in scientific notation.


import java.text.DecimalFormat;

// Java 1.4+ Compatible
//
// The following example code demonstrates converting a number 
// (double) into a formatted String in scientific notation setting
// the number of digits after the decimal place and in the exponent
//
public class FormatDecimalScientificNotation {

public static void main(String[] args) {

// speed of light in m/s
double number = 299792458;

// scientific notation, three decimal places, one exponent digit
DecimalFormat df = new DecimalFormat("0.000E0");
System.out.println(df.format(number));

// scientific notation, lower case e, two decimal places, two exponent digits
df = new DecimalFormat("0.00E00");
System.out.println(df.format(number).toLowerCase());

}

}



Here is the output of the example code:
2.998E8
3.00e08

No comments: