Java.text.Format and related class explanation

Source: Internet
Author: User
Tags dateformat locale parse error

Java.text.FormatFormat is an abstract base class for formatting locale-sensitive information, such as dates, messages, and numbers, directly known to have DateFormat, Messageformat, NumberFormat. Format defines a programming interface for formatting locale-sensitive objects into a string (using the Format method) and for re-parsing a string into an object (using the Parseobject method).
Typically, a format's Parseobject method must be able to parse any string that is formatted by its format method. However, there may be exceptions that cannot be resolved. For example, the format method might create two contiguous integers without delimiters in the middle, in which case the parseobject cannot determine which number belongs to. The Java platform provides three special format subclasses for formatted dates, messages, and numbers: DateFormat, Messageformat, and NumberFormat. A specific subclass must implement three methods:
Format (Object obj, StringBuffer toappendto, FieldPosition POS)
Formattocharacteriterator (Object obj)
Parseobject (String source, parseposition POS)
These general methods allow the object to be polymorphic parsed and formatted, and can also be used (as used by Messageformat). Subclasses often also provide additional format methods for specific input types, as well as parse methods for specific result types. Any parse method without the parseposition parameter should throw a parseexception when the input text does not have any text in the desired format at the beginning.
Most subclasses will also implement the following factory methods:
GetInstance get a useful format object for the current locale
getinstance (Locale) Gets a useful format object that is appropriate for the specified locale.
In addition, some subclasses may implement other getxxxxinstance methods for more specific control. For example, the NumberFormat class provides the Getpercentinstance and Getcurrencyinstance methods to obtain a special number formatter.
Subclasses of format if you allow programmers to create objects for different locales, such as getinstance (Locale), you must implement the following class methods:
public static locale[] Getavailablelocales ()
The last subclass defines a constant collection to identify the different fields in the format output. These constants are used to create a FieldPosition object that contains information in the object's identity field and its location in the formatting results. These constants should be named Item_field, where item identifies the field. For examples of these constants, see Era_field and its equivalents in DateFormat. The format is not usually synchronous. We recommend that you create a separate instance of the format for each thread. If multiple threads access one format at the same time, the other must remain externally synchronized. Java.text.FieldPosition Construction method Public fieldposition (int field) creates a FieldPosition object for the given field. Fields are identified by constants, and in different format subclasses, constant names generally end with _field.
Public fieldposition (Format.field attribute) creates a FieldPosition object for the given field constants. Fields are identified by constants defined in different format subclasses. This is equivalent to calling new FieldPosition (attribute,-1). Public FieldPosition (Format.field attribute,int fieldid) creates a FieldPosition object for the given field. The field is identified by a property constant from one of the subclasses of the field and an integer field ID defined by the subclass of format. When attribute is not NULL, the format subclass that needs to use field should take precedence over attribute and ignore FieldID. However, the old format subclass may not know the field and rely on FieldID. If the field does not have a corresponding integral type constant, FieldID should be-1. FieldPosition is a simple class that format and its subclasses use to identify fields in the formatted output (format (Object obj, StringBuffer toappendto, FieldPosition POS)).
FieldPosition keeps track of the two indexes of the field position in the format output: The index of the first character of the field and the index of the last character immediately following the field.
The format method in the different format classes requires a FieldPosition object as a parameter. Use this format method to perform partial formatting or to get formatted output information (such as field locations). A field can be identified in two ways, and the action is consistent, but the Format.field constant is more detailed and is recommended in this way:
1, through an integer constant whose name usually ends with _field. These constants are defined in different subclasses of format: NumberFormat
The static int Fraction_field           The field constants used to construct the FieldPosition object. The static int Integer_field           The field constants used to construct the FieldPosition object.
Example:
public static void Main (string[] args) {NumberFormat NumberFormat = numberformat.getinstance ();        StringBuffer stringBuffer1 = new StringBuffer ();        FieldPosition fieldposition = new FieldPosition (Numberformat.integer_field);        BigDecimal BigDecimal = new BigDecimal ("1.23456789");        StringBuffer1 = Numberformat.format (BigDecimal, StringBuffer1, fieldposition);        System.out.println ("StringBuffer1 =" + StringBuffer1); System.out.println ("integer:beginindex=" + fieldposition.getbeginindex () + ", endindex=" + fieldposition.getendindex (        ));        FieldPosition = new FieldPosition (Numberformat.fraction_field);        StringBuffer stringBuffer2 = new StringBuffer ();        StringBuffer2 = Numberformat.format (BigDecimal, StringBuffer2, fieldposition);        System.out.println ("StringBuffer2 =" + StringBuffer2); System.out.println ("fraction:beginindex=" + fieldposition.getbeginindex () + ", endindex=" + Fieldposition.getendindex    ()); }
StringBuffer1 = 1.235integer:beginindex=0,endindex=1stringbuffer2 = 1.235fraction:beginindex=2,endindex=5
2, through a Format.field constant: Numberformat.field
Static Numberformat.field CURRENCY           The constant that identifies the currency field. Static Numberformat.field Decimal_separator           The constant that identifies the decimal field. The static Numberformat.field EXPONENT           identifies a constant that refers to a number field. Static Numberformat.field Exponent_sign           The constant that identifies the exponential symbol (EXPONENT sign) field. Static Numberformat.field Exponent_symbol           The constant that identifies the exponential symbol (EXPONENT symbol) field. Static Numberformat.field fraction           The constant that identifies the small number field. Static Numberformat.field Grouping_separator           The constant that identifies the group separator field. The static Numberformat.field integer           identifies the constant of the integer field. Static Numberformat.field PERCENT           The constant that identifies the percentile field. Static Numberformat.field Permille           The constant that identifies the thousand-digit field. Static Numberformat.field           sign identifies the constant of the symbol field.
Example:
public static void Main (string[] args) {NumberFormat NumberFormat = numberformat.getinstance ();        StringBuffer stringBuffer1 = new StringBuffer ();        FieldPosition fieldposition = new FieldPosition (NumberFormat.Field.INTEGER);        BigDecimal BigDecimal = new BigDecimal ("1.23456789");        StringBuffer1 = Numberformat.format (BigDecimal, StringBuffer1, fieldposition);        System.out.println ("StringBuffer1 =" + StringBuffer1); System.out.println ("integer:beginindex=" + fieldposition.getbeginindex () + ", endindex=" + fieldposition.getendindex (        ));        FieldPosition = new FieldPosition (NumberFormat.Field.FRACTION);        StringBuffer stringBuffer2 = new StringBuffer ();        StringBuffer2 = Numberformat.format (BigDecimal, StringBuffer2, fieldposition);        System.out.println ("StringBuffer2 =" + StringBuffer2); System.out.println ("fraction:beginindex=" + fieldposition.getbeginindex () + ", endindex=" + Fieldposition.getendindex    ()); }
StringBuffer1 = 1.235integer:beginindex=0,endindex=1stringbuffer2 = 1.235fraction:beginindex=2,endindex=5
public static void Main (string[] args) {        DateFormat DateFormat = dateformat.getdatetimeinstance (Dateformat.long, Dateformat.long);        StringBuffer StringBuffer = new StringBuffer ();        FieldPosition pos = new FieldPosition (DateFormat.Field.DAY_OF_MONTH);        StringBuffer = Dateformat.format (New Date (), StringBuffer, POS);        System.out.println ("StringBuffer =" + StringBuffer);        System.out.println ("date_field:beginindex=" + pos.getbeginindex () + ", endindex=" + pos.getendindex ());    }
StringBuffer = June 28, 2016 11:07 A.M. 18 sec date_field:beginindex= 7,endindex=9

Java.text.ParsePositionParsePosition is a simple class used by format and its subclasses to track the current position during parsing. The Parseobject method in various format classes requires that the Parseposition object be used as a variable. When parsing a string with a different format, you can use the same parseposition because the index parameter records the current position. Parseposition also records the location of the parse error. Construction method Public parseposition (int index) creates a new parseposition with the given initial index. Example:
public static void Main (string[] args) {SimpleDateFormat SimpleDateFormat = new Simp        Ledateformat ("Yyyy-mm-dd");        String strings[] = {"xxx 2016-06-28 xxx1", "20160628 xxx2"};            for (int i = 0; i < strings.length; i++) {parseposition parseposition = new parseposition (4);//start processing from fourth bit            Date date = Simpledateformat.parse (Strings[i], parseposition);                Parse error, return NULL if (date = = null) {SYSTEM.OUT.PRINTLN ("Invalid Date:" + strings[i]);                SYSTEM.OUT.PRINTLN ("Parse Error index =" + Parseposition.geterrorindex ());                SYSTEM.OUT.PRINTLN ("Current index =" + Parseposition.getindex ());            Continue            } String substring = strings[i].substring (Parseposition.getindex ());        System.out.println ("date =" + Date + ", remainder:" + substring); }    }
Date =tue June 00:00:00 CST 2016, remainder: xxx1 Invalid Date: 20160628 xxx2 Parse Error index = 8 Current index =4
Java.text.NumberFormatNumberFormat is the abstract base class for all numeric formats. This class provides an interface for formatting and parsing numeric values. NumberFormat also provides methods to determine which locales have numeric formatting, and what their names are.
NumberFormat can be used to format and parse numeric values for any locale. Enables the code to be completely independent of the locale conventions of the decimal point, thousands separator, or even the specified number of decimal places, regardless of whether the numeric format is even decimal. How do I get an instance? NumberFormat a total of three instances, general values, currency values, percent values, each of which can be used in the default locale and the specified language environment. General values: getinstance () (Same as Getnumberinstance ()), getinstance (locale Inlocale) (same as getnumberinstance (locale Inlocale) ) Currency value: Getcurrencyinstance (), getcurrencyinstance (Locale Inlocale) percent value: getpercentinstance (), Getpercentinstance ( Locale inlocale) public static locale[] Getavailablelocales () returns an array of currently supported locales void Setcurrency (Currency Currency)
Sets the currency used for this numeric format when formatting currency values.
void Setgroupingused (Boolean newvalue)
Sets whether grouping is used in this format, that is, whether there are thousands separators (commas). void setmaximumfractiondigits (int newvalue)
Sets the maximum number of digits allowed for the number of decimal parts. independent of parsing.
void setmaximumintegerdigits (int newvalue)
Sets the maximum number of digits allowed for the integer portion of the number. independent of parsing.
void setminimumfractiondigits (int newvalue)
Sets the minimum number of digits allowed for the decimal portion of the count. independent of parsing.
void setminimumintegerdigits (int newvalue)
The minimum number of digits allowed for the integer portion of the set. independent of parsing.
void Setparseintegeronly (Boolean value)
Whether the set number should be parsed as an integer only. is not related to formatting. Example:
public static void Main (string[] args) throws Exception {//General value NumberFormat FORMAT1 = Numberformat.getnumb        Erinstance (); System.out.println (Format1.getmaximumintegerdigits ());//2147483647 System.out.println ( Format1.getminimumintegerdigits ());//1 System.out.println (Format1.getmaximumfractiondigits ());//3 System.out . println (Format1.getminimumfractiondigits ());//0 System.out.println (format1.isgroupingused ());//true System.        Out.println (Format1.isparseintegeronly ());//false System.out.println (Format1.format (10000000));//10,000,000 Default grouping System.out.println (Format1.format (10000000.000));//10,000,000 0 after the decimal point, discarded System.out.println (Format1.format (1 0000000.001));//10,000,000.001 System.out.println (Format1.format (10000000.0001));//10,000,000 default maximum size is 3 bits of Sy        Stem.out.println (Format1.parse ("10000000.001"));//1.0000000001e7 default can parse decimal format1.setparseintegeronly (TRUE); System.out.println (Format1.parse("10000000.001"));        /10000000//percent value NumberFormat format2 = Numberformat.getpercentinstance (); System.out.println (Format2.getmaximumintegerdigits ());//2147483647 System.out.println ( Format2.getminimumintegerdigits ());//1 System.out.println (Format2.getmaximumfractiondigits ());//0 System.out . println (Format2.getminimumfractiondigits ());//0 System.out.println (format2.isgroupingused ());//true System. Out.println (Format2.isparseintegeronly ());//false System.out.println (Format2.format (1.01));//101% System.out        . println (Format2.format (1.001));//100% The default maximum number of digits is 0 format2.setmaximumfractiondigits (1);        System.out.println (Format2.format (1.001));//100.1% System.out.println (Format2.parse ("100.1%"));//1.001 The default is to resolve decimals        Currency format NumberFormat FORMAT3 = Numberformat.getcurrencyinstance (); System.out.println (Format3.getmaximumintegerdigits ());//2147483647 System.out.println (Format3.getminimumintegeRdigits ());//1 System.out.println (Format3.getmaximumfractiondigits ());//2 System.out.println (Format3.getmini Mumfractiondigits ());//2 System.out.println (format3.isgroupingused ());//true System.out.println (Format3.ispa Rseintegeronly ());//false System.out.println (Format3.format (10000));//¥10,000.00 default locale is ZH_CN SYSTEM.OUT.PRI Ntln (Format3.parse ("¥10,000.00"));//10000}

Java.text.DecimalFormatDecimalFormat is a specific subclass of NumberFormat that is used to format decimal digits. The class has a variety of features that enable it to parse and format numbers in any locale, including support for Western, Arabic, and Indic numerals. Typically, you do not call DecimalFormat's constructor directly, and to get the decimalformat of a specific locale (including the default locale), you can call a factory method of NumberFormat, such as getinstance (). If you look at the source code will find getinstance () actually return is the DecimalFormat instance, because later version NumberFormat factory method may return a different subclass from DecimalFormat:
NumberFormat f = numberformat.getinstance (loc); if (f instanceof decimalformat) {     ((DecimalFormat) f). Setdecimalseparatoralwaysshown (True);
DecimalFormat contains a pattern and a set of symbols. The schema can be set directly using Applypattern () or indirectly using the API method. The symbols are stored in the decimalformatsymbols image. If you want to change symbols, such as decimal points, you can use the DecimalFormatSymbols associated with Decimalformate, which represents the set of symbols (such as decimal points, group separators, and so on) that are required to format numbers DecimalFormat. DecimalFormat creates a DecimalFormatSymbols instance of itself based on its locale data. If you need to change these symbols, you can get the DecimalFormatSymbols object from Decimalformat#getdecimalformatsymbols () and modify it. Usually programmers do not need to modify DecimalFormatSymbols. Special symbols
0 Digital. Arabic numerals, displayed as 0 if no number exists in the current position
# Digital. Arabic numerals, without affecting the value, if the current position is 0 or does not exist, it does not show
. Digital. Decimal separator or Currency decimal separator
- Digital. Minus sign
, Digital. Grouping separators
E Digital. Separates the mantissa and exponent in the scientific notation. No quotation marks in the prefix or suffix
; The child mode boundary. Separating positive and negative sub-patterns
% Prefix or suffix. Multiplied by 100 and displayed as a percentage
\u2030 Prefix or suffix. Multiplied by 1000 and displayed as thousand fractions
¤ (\U00A4) Prefix or suffix. Currency symbol, which is replaced by a currency sign. If two appears simultaneously, it is replaced with an international currency symbol. If it appears in a pattern, the currency decimal separator is used instead of the decimal separator
Prefix or suffix. Used to multibyte quotation marks for special words in a prefix or suffix, such as "# ' #" to format 123 as "#123". To create a single quotation mark itself, use two single quotes consecutively: "# o ' Clock"
Grammar1, prefixes and suffixes: symbols before and after the numbers, all Unicode characters except \ufffe, \UFFFF, and special characters. 2. The decimal separator and thousands separator should be different characters, otherwise it will not be possible to parse. 3. If you use a pattern with multiple grouping characters, the interval between the last delimiter and the end of the integer is the grouping size used.   So "#,##,###,####" = = "######,####" = = "##,####,####". Construction Method DecimalFormat ()
Creates a DecimalFormat using the default mode and the symbol for the default locale.
DecimalFormat (String pattern)
Creates a decimalformat with the symbol for the given pattern and default locale.
DecimalFormat (String pattern, decimalformatsymbols symbols)
Creates a decimalformat with the given pattern and symbol. Example:
public static void Main (string[] args) throws Exception {        DecimalFormatSymbols unusualsymbols = new DECIMALFORMATSYMB OLS ();        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);//1^2345|678    }

Java.text.Format and related class explanation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.