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");

// scientific notation, lower case e, two decimal places, two exponent digits
df = new DecimalFormat("0.00E00");



Here is the output of the example code:

No comments: