java.text.DecimalFormat學習筆記

java.text.DecimalFormat學習筆記

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale,To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's factory methods, such as getInstance(). In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat. If you need to customize the format object, do something like this:

 NumberFormat f = NumberFormat.getInstance(loc);
 if (f instanceof DecimalFormat) {
     ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
 }
 
A DecimalFormat comprises a pattern and a set of symbols. The pattern may be set directly using applyPattern(), or indirectly using the API methods. The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods, the pattern and symbols are read from localized ResourceBundles.

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. If you want to change formatting symbols, such as the decimal separator, you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. These classes offer a great deal of flexibility in the formatting of numbers, but they can make your code more complex.
The text that follows uses examples that demonstrate the DecimalFormat and DecimalFormatSymbols classes.


Patterns
You specify the formatting properties of DecimalFormat with a pattern String. The pattern determines what the formatted number looks like.
以下是DecimalFormat使用到的模板,這些模板的是遞歸解譯的。

DecimalFormat patterns have the following syntax:
 Pattern:
         PositivePattern
         PositivePattern ; NegativePattern
 PositivePattern:
         Prefixopt Number Suffixopt
 NegativePattern:
         Prefixopt Number Suffixopt
 Prefix:
         any Unicode characters except /uFFFE, /uFFFF, and special characters
 Suffix:
         any Unicode characters except /uFFFE, /uFFFF, and special characters
 Number:
         Integer Exponentopt
         Integer . Fraction Exponentopt
 Integer:
         MinimumInteger
         #
         # Integer
         # , Integer
 MinimumInteger:
         0
         0 MinimumInteger
         0 , MinimumInteger
 Fraction:
         MinimumFractionopt OptionalFractionopt
 MinimumFraction:
         0 MinimumFractionopt
 OptionalFraction:
         # OptionalFractionopt
 Exponent:
         E MinimumExponent
 MinimumExponent:
         0 MinimumExponentopt

A DecimalFormat pattern contains a positive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, numeric part, and suffix. The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign (code>'-' in most locales) is used as the negative subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit negative subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are all the same as the positive pattern. That means that "#,##0.0#;(#)" produces precisely the same behavior as "#,##0.0#;(#,##0.0#)".


value    pattern   output    Explanation 
123456.789  ###,###.###   123,456.789   The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator. 

123456.789   ###.##   123456.79   The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.
 
123.78   000000.000   000123.780   The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
 
12345.67   $###,###.###   $12,345.67   The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output. 

12345.67   /u00A5###,###.###  ¥12,345.67   The pattern specifies the currency sign for Japanese yen (¥) with the Unicode value 00A5. 

Altering the Formatting Symbols

You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others.
The next example demonstrates the DecimalFormatSymbols class by applying a strange format to a number. The unusual format is the result of the calls to the setDecimalSeparator, setGroupingSeparator, and setGroupingSize methods.

DecimalFormatSymbols unusualSymbols =
    new DecimalFormatSymbols(currentLocale);
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');

String strange = "#,##0.###";
DecimalFormat weirdFormatter =
               new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);

String bizarre = weirdFormatter.format(12345.678);
System.out.println(bizarre);

When run, this example prints the number in a bizarre format:

1^2345|678

Number Format Pattern Syntax

You can design your own format patterns for numbers by following the rules specified by the following BNF diagram:
pattern    := subpattern{;subpattern}
subpattern := {prefix}integer{.fraction}{suffix}
prefix     := '//u0000'..'//uFFFD' - specialCharacters
suffix     := '//u0000'..'//uFFFD' - specialCharacters
integer    := '#'* '0'* '0'
fraction   := '0'* '#'*

The notation used in the preceding diagram is explained in the following table:

Notation    Description
X*    0 or more instances of X
(X | Y)    either X or Y
X..Y    any character from X up to Y, inclusive
S - T    characters in S, except those in T
{X}    X is optional

 


Rounding
DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting.


see also
NumberFormat


例子:
import java.text.*;

public class Untitled1   {
  public static void main(String[] args) {

    //---------------------------------------------
    //定義一個數字格式化對象,格式化模板爲".##",即保留2位小數.
    DecimalFormat a = new DecimalFormat(".##");
    String s= a.format(333.335);
    System.err.println(s);
    //說明:如果小數點後面不夠2位小數,不會補零.參見Rounding小節
    //---------------------------------------------

    //-----------------------------------------------
    //可以在運行時刻用函數applyPattern(String)修改格式模板
    //保留2位小數,如果小數點後面不夠2位小數會補零
    a.applyPattern(".00");
    s = a.format(333.3);
    System.err.println(s);
    //------------------------------------------------

    //------------------------------------------------
    //添加千分號
    a.applyPattern(".##/u2030");
    s = a.format(0.78934);
    System.err.println(s);//添加千位符後,小數會進三位並加上千位符
    //------------------------------------------------

    //------------------------------------------------
    //添加百分號
    a.applyPattern("#.##%");
    s = a.format(0.78645);
    System.err.println(s);
    //------------------------------------------------

   //------------------------------------------------
    //添加前、後修飾字符串,記得要用單引號括起來
    a.applyPattern("'這是我的錢$',###.###'美圓'");
    s = a.format(33333443.3333);
    System.err.println(s);
    //------------------------------------------------

     //------------------------------------------------
    //添加貨幣表示符號(不同的國家,添加的符號不一樣
    a.applyPattern("/u00A4");
    s = a.format(34);
    System.err.println(s);
    //------------------------------------------------

    //-----------------------------------------------
    //定義正負數模板,記得要用分號隔開
     a.applyPattern("0.0;'@'-#.0");
     s = a.format(33);
     System.err.println(s);
     s = a.format(-33);
     System.err.println(s);
     //-----------------------------------------------
   
    //綜合運用,正負數的不同前後綴
    String pattern="'my moneny'###,###.##'RMB';'ur money'###,###.##'US'";
    a.applyPattern(pattern);
    System.out.println(a.format(1223233.456));
  }
}

總結:
要生成一個DecimalFormat對象,一般只要通過NumberFormat類工廠的getInstance()來取得一個NumberFormat對象再將其轉換成DecimalFormat對象,然後通過DecimalForat對象的applyPattern()來動態改變數據的現示格式模板,通過format()方法取得格式化後的數字。同時,DecimalFormat提供了許多的方法來返回格式化後的數字的某一部份,這些方法如:getNegativeSuffix()。這個類的難點主要是在模板的書寫及理解上。其實主要的就是針對一個數字的正負形式來設定不同的格式顯示。這裏要特別注意的是使用在模板上的特殊字符代表有特殊的意義,如下表所示:
Symbol   Description
0   a digit
#   a digit, zero shows as absent
.   placeholder for decimal separator
,   placeholder for grouping separator
E  separates mantissa and exponent for exponential formats
;   separates formats
-   default negative prefix
%   multiply by 100 and show as percentage
?   multiply by 1000 and show as per mille
¤   currency sign; replaced by currency symbol; if doubled, replaced by international currency symbol; if present in a pattern, the monetary decimal separator is used instead of the decimal separator 
X   any other characters can be used in the prefix or suffix
'   used to quote special characters in a prefix or suffix

例如:如果模板中含有#,意思是指這個#號可代表一個或多個數字如果該位的數字是零的話則省略該位。另:注意“#,##0.0#;(#)”這個模板的意思是指數字的負數形式跟正數的一樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章