The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples] > Numbers  [5 examples]

e313. Formatting a Number in Exponential Notation

The `E' symbol specifies that a number should be formatted in exponential notation. The symbol also separates the mantissa from the exponent. The symbol must be followed by one or more `0' symbols. The number of `0' symbols specifies the minimum number of digits used to display the exponent.
    // Using only 0's to the left of E forces no decimal point
    NumberFormat formatter = new DecimalFormat("0E0");
    String s = formatter.format(-1234.567);  // -1E3
    
    formatter = new DecimalFormat("00E00");
    s = formatter.format(-1234.567);         // -12E02
    
    formatter = new DecimalFormat("000E00");
    s = formatter.format(-1234.567);         // -123E01
    
    formatter = new DecimalFormat("0000000000E0");
    s = formatter.format(-1234.567);         // -1234567000E-6
    
    
    // Force minimum number of digits to left and right of decimal point
    formatter = new DecimalFormat("0.0E0");
    s = formatter.format(-1234.567);         // -1.2E3
    
    formatter = new DecimalFormat("00.00E0");
    s = formatter.format(-1234.567);         // -12.35E2
    s = formatter.format(-.1234567);         // -12.35E-2
    
    
    // The number of #'s to the left of the decimal point (if any) specifies
    // the multiple of the exponent. The total number of #'s (left and right)
    // of the decimal point) specifies, the maximum number of digits to display
    formatter = new DecimalFormat("#E0");    // exponent can be any value
    s = formatter.format(-1234.567);         // -.1E4
    s = formatter.format(-.1234567);         // -.1E0
    
    formatter = new DecimalFormat("##E0");   // exponent must be multiple of 2
    s = formatter.format(-1234.567);         // -12E2
    s = formatter.format(-123.4567);         // -1.2E2
    s = formatter.format(-12.34567);         // -12E0
    
    formatter = new DecimalFormat("###E0");  // exponent must be multiple of 3
    s = formatter.format(-1234.567);         // -1.23E3
    s = formatter.format(-123.4567);         // -123E0
    s = formatter.format(-12.34567);         // -12.3E0
    s = formatter.format(-1.234567);         // -12.3E0
    s = formatter.format(-.1234567);         // -123E-3

 Related Examples
e311. Formatting a Number Using a Custom Format
e312. Formatting and Parsing a Number for a Locale
e314. Formatting and Parsing Locale-Specific Currency
e315. Formatting and Parsing a Locale-Specific Percentage

See also: Dates    Messsages    Times    Words and Sentences   


© 2002 Addison-Wesley.