Generated by
JDiff

java.text Documentation Differences

This file contains all the changes in documentation in the package java.text as colored differences. Deletions are shown like this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.

Class CharacterIterator, char DONE

Constant that is returned when the iterator has reached either the end or the beginning of the text. The unicode 2.0 standard statesvalue thatis '\\uFFFF' isthe an"not invalida unicodecharacter" value andwhich should not occur in any valid unicodeUnicode string.

Class ChoiceFormat

A ChoiceFormat allows you to attach a format to a range of numbers. It is generally used in a MessageFormat for handling plurals. The choice is specified with an ascending list of doubles where each item specifies a half-open interval up to the next item:
 X matches j if and only if limit[j] <= X < limit[j+1] 
If there is no match then either the first or last index is used depending on whether the number (X) is too low or too high. If the limit array is not in ascending order the results of formatting will be incorrect. ChoiceFormat also accepts \\\u221E as equivalent to infinity(INF).

Note: ChoiceFormat differs from the other Format classes in that you create a ChoiceFormat object with a constructor (not with a getInstance style factory method). The factory methods aren't necessary because ChoiceFormat doesn't require any complex setup for a given locale. In fact ChoiceFormat doesn't implement any locale specific behavior.

When creating a ChoiceFormat you must specify an array of formats and an array of limits. The length of these arrays must be the same. For example

Here is a simple example that shows formatting and parsing:

 double[] limits = {1 2 3 4 5 6 7}; String[] monthNames = {"Sun" "Mon" "Tue" "Wed" "Thur" "Fri" "Sat"}; ChoiceFormat form = new ChoiceFormat(limits monthNames); ParsePosition status = new ParsePosition(0); for (double i = 0.0; i <= 8.0; ++i) { status.setIndex(0); System.out.println(i + " -> " + form.format(i) + " -> " + form.parse(form.format(i) status)); } 
Here is a more complex example with a pattern format:
 double[] filelimits = {0 1 2}; String[] filepart = {"are no files" "is one file" "are {2} files"}; ChoiceFormat fileform = new ChoiceFormat(filelimits filepart); Format[] testFormats = {fileform null NumberFormat.getInstance()}; MessageFormat pattform = new MessageFormat("There {0} on {1}"); pattform.setFormats(testFormats); Object[] testArgs = {null "ADisk" null}; for (int i = 0; i < 4; ++i) { testArgs[0] = new Integer(i); testArgs[2] = testArgs[0]; System.out.println(pattform.format(testArgs)); } 

Specifying a pattern for ChoiceFormat objects is fairly straightforward. For example:

 ChoiceFormat fmt = new ChoiceFormat( "-1#is negative| 0#is zero or fraction | 1#is one |1.0<is 1+ |2#is two |2<is more than 2."); System.out.println("Formatter Pattern : " + fmt.toPattern()); System.out.println("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY)); System.out.println("Format with -1.0 : " + fmt.format(-1.0)); System.out.println("Format with 0 : " + fmt.format(0)); System.out.println("Format with 0.9 : " + fmt.format(0.9)); System.out.println("Format with 1.0 : " + fmt.format(1)); System.out.println("Format with 1.5 : " + fmt.format(1.5)); System.out.println("Format with 2 : " + fmt.format(2)); System.out.println("Format with 2.1 : " + fmt.format(2.1)); System.out.println("Format with NaN : " + fmt.format(Double.NaN)); System.out.println("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY)); 
And the output result would be like the following:
 
Format with -INF : is negative Format with -1.0 : is negative Format with 0 : is zero or fraction Format with 0.9 : is zero or fraction Format with 1.0 : is one Format with 1.5 : is 1+ Format with 2 : is two Format with 2.1 : is more than 2. Format with NaN : is negative Format with +INF : is more than 2.

Synchronization

Choice formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see DecimalFormat @see MessageFormat @version 1.22 09/21/98 @author Mark Davis Class ChoiceFormat, constructor ChoiceFormat(String)

Constructs with limits and corresponding formats based on the pattern. @see #applyPattern

Class CollationElementIterator

The CollationElementIterator class is used as an iterator to walk through each character of an international string. Use the iterator to return the ordering priority of the positioned character. The ordering priority of a character which we refer to as a key defines how a character is collated in the given collation object.

For example consider the following in Spanish:

 "ca" -> the first key is key('c') and second key is key('a'). "cha" -> the first key is key('ch') and second key is key('a'). 
And in German
 "äb"-> the first key is key('a') the second key is key('e') and the third key is key('b'). 
The key of a character is an integer composed of primary order(short) secondary order(byte) and tertiary order(byte). Java strictly defines the size and signedness of its primitive data types. Therefore the static functions primaryOrder secondaryOrder and tertiaryOrder return int short and short respectively to ensure the correctness of the key value.

Example of the iterator usage

 // get the first key of the string String strtestString = "This is a test"; CollationElementIteratorRuleBasedCollator cruleBasedCollator = new CollationElementIterator(str 0 str.length(RuleBasedCollator) Collator.getInstance(); CollationElementIterator collationElementIterator = ruleBasedCollator.getCollationElementIterator(testString); int primaryOrder = CollationElementIterator.primaryOrder(c-collationElementIterator.next()); 

CollationElementIterator.next returns the collation order of the next character. A collation order consists of primary order secondary order and tertiary order. The data type of the collation order is int. The first 16 bits of a collation order is its primary order; the next 8 bits is the secondary order and the last 8 bits is the tertiary order. @see Collator @see RuleBasedCollator @version 1.24 07/27/98 @author Helena Shih Laura Werner Richard Gillam


Class CollationKey

A CollationKey represents a String under the rules of a specific Collator object. Comparing two CollationKeys returns the relative order of the Strings they represent. Using CollationKeys to compare Strings is generally faster than using Collator.compare. Thus when the Strings must be compared multiple times for example when sorting a list of Strings. It's more efficient to use CollationKeys.

You can not create CollationKeys directly. Rather generate them by calling Collator.getCollationKey. You can only compare CollationKeys generated from the same Collator object.

Generating a CollationKey for a String involves examining the entire String and converting it to series of bits that can be compared bitwise. This allows fast comparisons once the keys are generated. The cost of generating keys is recouped in faster comparisons when Strings need to be compared many times. On the other hand the result of a comparison is often determined by the first couple of characters of each String. Collator.compare examines only as many characters as it needs which allows it to be faster when doing single comparisons.

The following example shows how CollationKeys might be used to sort a list of Strings.

 // Create an array of CollationKeys for the Strings to be sorted. Collator myCollator = Collator.getInstance(); CollationKey[] keys = new CollationKey[3]; keys[0] = myCollator.getCollationKey("Tom"); keys[1] = myCollator.getCollationKey("Dick"); keys[2] = myCollator.getCollationKey("Harry"); sort( keys ); 
//...
// Inside body of sort routine compare keys this way if( keys[i].compareTo( keys[j] ) > 0 ) // swap keys[i] and keys[j]
//...
// Finally when we've returned from sort. System.out.println( keys[0].getSourceString() ); System.out.println( keys[1].getSourceString() ); System.out.println( keys[2].getSourceString() );
@see Collator @see RuleBasedCollator @version 1.14 0115 12/1903/0001 @author Helena Shih

Class Collator

The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

Collator is an abstract base class. Subclasses implement specific collation strategies. One subclass RuleBasedCollator is currently provided with the Java 2 platform and is applicable to a wide set of languages. Other subclasses may be created to handle more specialized needs.

Like other locale-sensitive classes you can use the static factory method getInstance to obtain the appropriate Collator object for a given locale. You will only need to look at the subclasses of Collator if you need to understand the details of a particular collation strategy or if you need to modify that strategy.

The following example shows how to compare two strings using the Collator for the default locale.

 // Compare two strings in the default locale Collator myCollator = Collator.getInstance(); if( myCollator.compare("abc" "ABC") <0 ) System.out.println("abc is less than ABC"); else System.out.println("abc is greater than or equal to ABC"); 

You can set a Collator's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY SECONDARY TERTIARY and IDENTICAL. The exact assignment of strengths to language features is locale dependant. For example in Czech "e" and "f" are considered primary differences while "e" and "ê" are secondary differences "e" and "E" are tertiary differences and "e" and "e" are identical. The following shows how both case and accents could be ignored for US English.

 //Get the Collator for US English and set its strength to PRIMARY Collator usCollator = Collator.getInstance(Locale.US); usCollator.setStrength(Collator.PRIMARY); if( usCollator.compare("abc" "ABC") == 0 ) { System.out.println("Strings are equivalent"); } 

For comparing Strings exactly once the compare method provides the best performance. When sorting a list of Strings however it is generally necessary to compare each String multiple times. In this case CollationKeys provide better performance. The CollationKey class converts a String to a series of bits that can be compared bitwise against other CollationKeys. A CollationKey is created by a Collator object for a given String.
Note: CollationKeys from different Collators can not be compared. See the class description for CollationKey for an example using CollationKeys. @see RuleBasedCollator @see CollationKey @see CollationElementIterator @see Locale @version 1.27 0132 12/1903/0001 @author Helena Shih Laura Werner Richard Gillam

Class Collator, int CANONICAL_DECOMPOSITION

Decomposition mode value. With CANONICAL_DECOMPOSITION set characters that are canonical variants according to Unicode 2.0 will be decomposed for collation. This is the default setting and should be used to get correct collation of accented characters.

CANONICAL_DECOMPOSITION corresponds to Normalization Form D as described in Unicode Technical Report #15. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class Collator, int FULL_DECOMPOSITION

Decomposition mode value. With FULL_DECOMPOSITION set both Unicode canonical variants and Unicode compatibility variants will be decomposed for collation. This causes not only accented characters to be collated but also characters that have special formats to be collated with their norminal form. For example the half-width and full-width ASCII and Katakana characters are then collated together. FULL_DECOMPOSITION is the most complete and therefore the slowest decomposition mode.

FULL_DECOMPOSITION corresponds to Normalization Form DCKD as described in Unicode Technical Report #15. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class Collator, int NO_DECOMPOSITION

Decomposition mode value. With NO_DECOMPOSITION set accented characters will not be decomposed for collation. This is the default setting and provides the fastest collation but will only produce correct results for languages that do not use accents. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class DateFormat

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass such as SimpleDateFormat allows for formatting (i.e. date -> text) parsing (text -> date) and normalization. The date is represented as a Date object or as the milliseconds since January 1 1970 00:00:00 GMT.

DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given loaclelocale and a number of formatting styles. The formatting styles include FULL LONG MEDIUM and SHORT. More detail and examples of using these styles are provided in the method descriptions.

DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months days of the week or even the calendar format: lunar vs. solar.

To format a date for the current Locale use one of the static factory methods:

 myString = DateFormat.getDateInstance().format(myDate); 

If you are formatting multiple numbersdates it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

 DateFormat df = DateFormat.getDateInstance(); for (int i = 0; i  

To format a numberdate for a different Locale specify it in the call to getDateInstance().

 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG Locale.FRANCE); 

You can use a DateFormat to parse also.

 myDate = df.parse(myString); 

Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale but generally:

  • SHORT is completely numeric such as 12.13.52 or 3:30pm
  • MEDIUM is longer such as Jan 12 1952
  • LONG is longer such as January 12 1952 or 3:30:32pm
  • FULL is pretty completely specified such as Tuesday April 12 1952 AD or 3:30:42pm PST.

You can also set the time zone on the format if you wish. If you want even more control over the format or parsing (or want to give your users more control) you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to

  • progressively parse through pieces of a string.
  • align any particular field or find out where it is for selection on the screen.

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see Format @see NumberFormat @see SimpleDateFormat @see java.util.Calendar @see java.util.GregorianCalendar @see java.util.TimeZone @version 1.38 0145 12/1903/0001 @author Mark Davis Chen-Lieh Huang Alan Liu

Class DateFormat, StringBuffer format(Date, StringBuffer, FieldPosition)

Formats a Date into a date/time string. @param date a Date to be formatted into a date/time string. @param toAppendTo the string buffer for the returning date/time string. @param fieldPosition keeps track of the position of the field within the returned string. On input: an alignment field if desired. On output: the offsets of the alignment field. For example given a time text "1996.07.10 AD at 15:08:56 PDT" if the given fieldPosition is DateFormat.YEAR_FIELD the begin index and end index of fieldPosition will be set to 0 and 4 respectively. Notice that if the same time field appears more than once in a pattern the fieldPosition will be set for the first occurenceoccurrence of that time field. For instance formatting a Date to the time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD the begin index and end index of fieldPosition will be set to 5 and 8 respectively for the first occurenceoccurrence of the timezone pattern character 'z'. @return the formatted date/time string.
Class DateFormat, StringBuffer format(Object, StringBuffer, FieldPosition)

Overrides Format. Formats a time object into a time string. Examples of time objects are a time value expressed in milliseconds and a Date object. @param obj must be a Number or a Date. @param toAppendTo the string buffer for the returning time string. @return the formatted time string. @param fieldPosition keeps track of the position of the field within the returned string. On input: an alignment field if desired. On output: the offsets of the alignment field. For example given a time text "1996.07.10 AD at 15:08:56 PDT" if the given fieldPosition is DateFormat.YEAR_FIELD the begin index and end index of fieldPosition will be set to 0 and 4 respectively. Notice that if the same time field appears more than once in a pattern the fieldPosition will be set for the first occurenceoccurrence of that time field. For instance formatting a Date to the time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD the begin index and end index of fieldPosition will be set to 5 and 8 respectively for the first occurenceoccurrence of the timezone pattern character 'z'. @see java.text.Format
Class DateFormat, Date parse(String)

ParseParses text from the beginning of the given string to produce a date/time. The method may not use the entire text of the given string.

See the ParsePosition) method for more information on date parsing. @param text Thesource A date/timeString stringwhose tobeginning should be parsed. @return A Date or nullparsed iffrom the input could not be parsedstring. @exception ParseException Ifif the givenbeginning of the specified string cannot be parsed as a date. @see #parse(String ParsePosition)

Class DateFormat, Date parse(String, ParsePosition)

Parse a date/time string according to the given parse position. For example a time text "07/10/96 4:5 PM PDT" will be parsed into a Date that is equivalent to Date(837039928046).

By default parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false). @see java.text.DateFormat#setLenient(boolean) @param textsource The date/time string to be parsed @param pos On input the position at which to start parsing; on output the position at which parsing terminated or the start position if the parse failed. @return A Date or null if the input could not be parsed

Class DateFormat, Object parseObject(String, ParsePosition)

Parse aParses text date/timefrom a string intoto anproduce a ObjectDate. This convenience

The method simplyattempts callsto parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (Stringparsing does not necessarily use all characters up to the end of the string) and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs then the index of pos is not changed the error index of pos is set to the index of the character where the error occurred and null is returned.

See the ParsePosition) method for more information on date parsing. @seeparam #parse(source A String part of which should be parsed. @param pos A ParsePosition) object with index and error index information as described above. @return A Date parsed from the string. In case of error returns null. @exception NullPointerException if pos is null.


Class DateFormatSymbols

DateFormatSymbols is a public class for encapsulating localizable date-time formatting data such as the names of the months the names of the days of the week and the time zone data. DateFormat and SimpleDateFormat both use DateFormatSymbols to encapsulate this information.

Typically you shouldn't use DateFormatSymbols directly. Rather you are encouraged to create a date-time formatter with the DateFormat class's factory methods: getTimeInstance getDateInstance or getDateTimeInstance. These methods automatically create a DateFormatSymbols for the formatter so that you don't have to. After the formatter is created you may modify its format pattern using the setPattern method. For more information about creating formatters using DateFormat's factory methods see DateFormat

If you decide to create a date-time formatter with a specific format pattern for a specific locale you can do so with:

 new SimpleDateFormat(aPattern new DateFormatSymbols(aLocale)). 

DateFormatSymbols objects are clonablecloneable. When you obtain a DateFormatSymbols object feel free to modify the date-time formatting data. For instance you can replace the localized date-time format pattern characters with the ones that you feel easy to remember. Or you can change the representative cities to your favorite ones.

New DateFormatSymbols subclasses may be added to support SimpleDateFormat for date-time formatting for additional locales. @see DateFormat @see SimpleDateFormat @see java.util.SimpleTimeZone @version 1.3239 0112/1903/0001 @author Chen-Lieh Huang

Class DateFormatSymbols, String[] getAmPmStrings()

Gets ampm strings. For example: "AM" and "PM". @return the weekdayampm strings.

Class 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 including support for Western Arabic and Indic digits. It also supports different kinds of numbers including integers (123) fixed-point numbers (123.4) scientific notation (1.23E4) percentages (12%) and currency amounts ($123). All of these can be localized.

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 in the. package

Patterns

java.text.resourceDecimalFormat. Example // Print out a numberpatterns usinghave the localized number currency // and percent format for each locale Locale[] locales = NumberFormat.getAvailableLocales(); double myNumber = -1234.56; NumberFormat form; forfollowing (intsyntax: j=0;
 j;Pattern: ++j)PositivePattern {PositivePattern System.out.println("FORMAT"); forNegativePattern (intPositivePattern: iPrefixopt =Number 0;Suffixopt iNegativePattern: locales.length;Prefixopt ++i)Number {Suffixopt ifPrefix: (locales[i].getCountry().length()any ==Unicode 0)characters {except continue\; // Skip language-onlyuFFFE locales } System.out.print(locales[i].getDisplayName())\; switchuFFFF (j)and { casespecial characters 0Suffix: form = NumberFormat.getInstance(locales[i]); break; case 1:any form =Unicode characters NumberFormat.getCurrencyInstance(locales[i]);except break\; default: form =uFFFE NumberFormat.getPercentInstance(locales[i])\;uFFFF break;and } tryspecial characters {Number: //Integer AssumeExponentopt formInteger is. aFraction DecimalFormatExponentopt System.out.print("Integer: " + ((DecimalFormat)MinimumInteger form).toPattern()# +# "Integer -# "Integer +MinimumInteger: form.format(myNumber));0 }0 catchMinimumInteger (IllegalArgumentException0 e)MinimumInteger {}Fraction: tryMinimumFractionopt {OptionalFractionopt System.out.println("MinimumFraction: -0 "MinimumFractionopt +OptionalFraction: form.parse(form.format(myNumber)));# }OptionalFractionopt catchExponent: (ParseExceptionE e)MinimumExponent {}MinimumExponent: }0 }MinimumExponentopt 

Patterns A DecimalFormat pattern contains a postivepositive 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#)".

The prefixes suffixes and various symbols used for infinity digits thousands separators decimal separators etc. may be set to arbitrary values and they will appear properly during formatting. However care must be taken that the symbols and strings do not conflict or parsing will be unreliable. For example either the positive and negative prefixes or the suffixes must be distinct for DecimalFormat.parse() to be able to distinguish positive from negative values. (If they are identical then DecimalFormat will behave as if no negative subpattern was specified.) Another example is that the decimal separator and thousands separator should be distinct characters or parsing will be impossible.

The grouping separator is commonly used for thousands but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters such as 3 for 100 000 000 or 4 for 1 0000 0000. If you supply a pattern with multiple grouping characters the interval between the last one and the end of the integer is the one that is used. So "# ## ### ####" == "###### ####" == "## #### ####". Illegal patterns

Special suchPattern asCharacters

"#.#.#"

Many orcharacters "#.###in ###"a will causepattern are DecimalFormattaken toliterally; throw anthey are IllegalArgumentExceptionmatched with a message that describes the problemduring parsing and output unchanged during formatting. Parsing DecimalFormat parses all UnicodeSpecial characters that representon decimal digits as defined bythe other hand stand for Character.digit().other In additioncharacters strings DecimalFormator also recognizesclasses of ascharacters. digits the ten consecutive characters starting with the localized zero digit definedThey must be quoted unless noted otherwise if they are to appear in the DecimalFormatSymbols object. During formatting theprefix DecimalFormatSymbols-basedor digits are outputsuffix as literals.

DecimalFormat.parse returns aThe subclass ofcharacters listed java.lang.Numberhere representing the parsedare used in numericnon-localized stringpatterns. DecimalFormat chooses the most economical subclass thatLocalized can representpatterns use the numeric string. This means mostcorresponding integer values are returnedcharacters taken from this asformatter's LongDecimalFormatSymbols objects noobject matter how they areinstead and these characters written:lose "17"their andspecial "17status.000" both parse toTwo Long(17).exceptions Values that cannot fit into aare the currency sign and quote Longwhich are returned asnot Doubleslocalized. This includes

values with astring. Doing sothe"10
Symbol fractionalLocation partLocalized infiniteMeaning values
NaN0 andNumber theYes valueDigit -0.0.
DecimalFormat# does not decideNumber whetherYes toDigit return azero shows Doubleas or aabsent
Long. basedNumber onYes theDecimal presence of aseparator or monetary decimal separator in the source
- wouldNumber preventYes integersMinus that overflowsign
mantissa ofNumber aYes doubleGrouping such asseparator
E 000Number 000Yes 000Separates 000mantissa 000.00"and from being parsed accuratelyexponent in scientific notation. Currently theNeed only classes thatnot be quoted DecimalFormatin returns areprefix or Longsuffix. and
Double; but callers should not rely onSubpattern this.boundary CallersYes maySeparates use thepositive and Numbernegative methodssubpatterns doubleValue
longValue% etc. to obtain the type theyPrefix want.or Ifsuffix DecimalFormat.parse(StringYes ParsePosition)Multiply fails to parse a string it returnsby 100 and show as percentage
null\u2030 leaves thePrefix ParsePositionor indexsuffix unchangedYes andMultiply sets theby 1000 ParsePositionand errorshow index.as The convenience methodper mille
DecimalFormat.parse(String)¤ indicates parse failure by throwing a (ParseException\u00A4. Special) ValuesPrefix NaNor issuffix formattedNo asCurrency a single character typicallysign replaced by currency \uFFFDsymbol. This characterIf is determineddoubled replaced by theinternational DecimalFormatSymbolscurrency objectsymbol. This is theIf only value for whichpresent in a pattern the prefixes andmonetary suffixes are notdecimal separator is used. Infinity is formattedinstead as a singleof the decimal characterseparator. typically
\u221E' with the positivePrefix or negative prefixes andsuffix suffixesNo applied.Used The infinity character is determined by theto quote special characters in a prefix DecimalFormatSymbolsor object.suffix Negativefor zero (example "-0'#'#") parsesformats 123 to Double(-0.0)"#123". unlessTo isParseIntegerOnly()create is true in which case it parsesa single quote itself use two in toa row: Long(0)"# o''clock".

Scientific Notation

Numbers in scientific notation are expressed as the product of a mantissa and a power of ten for example 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 < x <10.0 but it need not be. DecimalFormat can be instructed to format and parse scientific notation only via a pattern; there is currently no factory method that creates a scientific notation format. In a pattern the exponent character immediately followed by one or more digit characters indicates scientific notation. Example: "0.###E0" formats the number 1234 as "1.234E3".

Pattern

Rounding

SyntaxDecimalFormat uses patternhalf-even :=rounding pos_pattern{';'(see negROUND_pattern} posHALF_pattern :=EVEN {prefix}number{suffix}for neg_patternformatting. :=

Digits

{prefix}number{suffix}For numberformatting :=DecimalFormat integer{'.'uses fraction}{exponent}the prefixten :=consecutive '\u0000'..'\uFFFD'characters -starting special_characterswith suffixthe :=localized '\u0000'..'\uFFFD'zero -digit special_charactersdefined integerin :=the min_intDecimalFormatSymbols |object '#'as |digits. '#'For integer |parsing these '#'digits ' ' integeras well as min_intall :=Unicode '0'decimal |digits '0'as min_intdefined |by '0'Character.digit 'are 'recognized. min_int

Special fractionValues

:=

NaN '0'*is '#'*formatted exponentas :=a 'E'single '0'character '0'*typically &#3292; Notation: X* 0 or more instances of X { X } 0 or 1 instances of X X | Y either X or Y X.uFFFD.Y anyThis character fromis X up todetermined by the YDecimalFormatSymbols inclusiveobject. S - T characters in S except those in T This is the only value for which the prefixes and suffixes Specialare Patternnot Charactersused.

Many charactersInfinity is informatted as a pattern are takensingle character typically literally\; theyu221E are matched during parsing and output unchanged during formattingwith the positive or negative prefixes and suffixes applied. SpecialThe characters on the other hand standinfinity character is determined by the forDecimalFormatSymbols otherobject. characters

Negative stringszero or("-0") classes ofparses to charactersDouble(-0. They must be quoted0) unless noted otherwise if they areisParseIntegerOnly() to appearis true in thewhich prefix or suffix ascase it parses to literalsLong(0). The

Synchronization

characters listed here

Decimal formats are used ingenerally non-localizednot patternssynchronized. Localized patterns use the corresponding characters taken from this formatter'sIt DecimalFormatSymbolsis object instead and these characters lose their special statusrecommended to create separate format instances for each thread. TwoIf exceptions are the currency sign and quote which are not localizedmultiple threads access a format concurrently it must be synchronized externally.

Example

SymbolLocationLocalized
 Meaning// 0NumberYDigitPrint #NumberYDigitout zero shows asa number using absentthe .NumberYDecimallocalized separator or monetarynumber integer currency decimal// separatorand -NumberYMinuspercent signformat for NumberYGroupingeach separatorlocale ENumberYLocale[] Separateslocales mantissa= andNumberFormat.getAvailableLocales(); exponent in scientificdouble myNumber = notation-1234.56; NeedNumberFormat notform; befor quoted(int inj=0; prefixj<; or++j) suffix.{ System.out.println("FORMAT");Subpattern boundaryY Separatesfor positive(int and negativei = subpatterns0; %Prefixi or<locales.length; suffixYMultiply++i) by 100{ if and(locales[i].getCountry().length() show== as0) percentage{ \continue;u2030Prefix or suffixY Multiply by 1000 and// showSkip aslanguage-only perlocales mille} ¤System.out.print(\u00A4locales[i].getDisplayName()Prefix); orswitch suffixN(j) Currency{ signcase replaced0: by currency symbolform = NumberFormat. IfgetInstance(locales[i]); doubledbreak; replacedcase by1: international currency symbolform = NumberFormat. If present in a patterngetIntegerInstance(locales[i]); thebreak; monetarycase decimal2: separator isform = usedNumberFormat.getCurrencyInstance(locales[i]); insteadbreak; ofdefault: the decimal separatorform = NumberFormat. 'Prefix orgetPercentInstance(locales[i]); suffixNbreak; Used} toif quote(form specialinstanceof charactersDecimalFormat) in{ aSystem.out.print(": prefix or" + suffix((DecimalFormat) forform).toPattern()); example} "'#'#System.out.print(" formats-> 123 to" + "#123"form.format(myNumber)); To createtry { aSystem.out.println(" single-> quote itself" + useform.parse(form.format(myNumber))); two in} catch a(ParseException row:e) "#{} o''clock".} } 
@see java.text.FormatJava Tutorial @see java.text.NumberFormat @see java.text.ChoiceFormatDecimalFormatSymbols @see java.text.ParsePosition @version 1.59 0268 12/0903/01 @author Mark Davis @author Alan Liu
Class DecimalFormat, constructor DecimalFormat()

CreateCreates a DecimalFormat using the default pattern and symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance

Class DecimalFormat, constructor DecimalFormat(String)

CreateCreates a DecimalFormat fromusing the given pattern and the symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @param pattern A non-localized pattern string. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance

Class DecimalFormat, constructor DecimalFormat(String, DecimalFormatSymbols)

CreateCreates a DecimalFormat fromusing the given pattern and symbols. Use this constructor when you need to completely customize the behavior of the format.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getInstance or getCurrencyInstance. If you need only minor adjustments to a standard format you can modify the format returned by a NumberFormat factory method. @param pattern a non-localized pattern string @param symbols the set of symbols to be used @exception NullPointerException if any of the given arguments is null @exception IllegalArgumentException if the given pattern is invalid @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance @see java.text.DecimalFormatSymbols

Class DecimalFormat, void applyLocalizedPattern(String)

Apply the given pattern to this Format object. The pattern is assumed to be in a localized notation. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers use a second pattern separated by a semicolon

Example "# #00.0#" -> 1 234.56

This means a minimum of 2 integer digits 1 fraction digit and a maximum of 2 fraction digits.

Example: "# #00.0#;(# #00.0#)" for negatives in paranthesesparentheses.

In negative patterns the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid.

Class DecimalFormat, void applyPattern(String)

Apply the given pattern to this Format object. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers use a second pattern separated by a semicolon

Example "# #00.0#" -> 1 234.56

This means a minimum of 2 integer digits 1 fraction digit and a maximum of 2 fraction digits.

Example: "# #00.0#;(# #00.0#)" for negatives in paranthesesparentheses.

In negative patterns the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid.

Class DecimalFormat, StringBuffer format(double, StringBuffer, FieldPosition)

Formats a double to produce a string. @param number The double to format @param toAppendToresult where the text is to be appended @param fieldPosition On input: an alignment field if desired. On output: the offsets of the alignment field. @return The value passed in as theformatted result parameternumber string @see java.text.FieldPosition
Class DecimalFormat, StringBuffer format(long, StringBuffer, FieldPosition)

Format a long to produce a string. @param number The long to format @param toAppendToresult where the text is to be appended @param fieldPosition On input: an alignment field if desired. On output: the offsets of the alignment field. @return The value passed in as theformatted result parameternumber string @see java.text.FieldPosition
Class DecimalFormat, Number parse(String, ParsePosition)

Returns an instanceParses text from ofa string to produce a Number. with a value matching

The method attempts to parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string) and the parsed number is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs then the index of pos is not changed the error index of pos is set to the index of the character where the error occurred and null is returned.

The most economical subclass that can represent all the bits of the sourcenumber given by the string is chosen. @paramMost text theinteger values stringare returned as Long objects no matter how they are written: "17" and "17.000" both parse to beLong(17). parsedValues @paramthat parsePosition on entrycannot fit into wherea Long are returned as Doubles. This includes values with a fractional part infinite values NaN and the value -0.0. DecimalFormat does not decide whether to beginreturn a parsing;Double or a Long based on exitthe presence justof a decimal pastseparator in the lastsource parsedstring. characterDoing so would prevent integers that overflow the mantissa of a double such as "10 000 000 000 000 000.00" If parsingfrom being failsparsed accurately. Currently the index will notonly classes that moveparse returns are Long and Double but callers should not rely on this. Callers may use the Number methods doubleValue longValue etc. to obtain the type they want.

DecimalFormat parses all Unicode characters that represent decimal digits as defined by Character.digit(). In addition DecimalFormat also recognizes as digits the ten consecutive characters starting with the localized zero digit defined in the DecimalFormatSymbols object. @param text the string to be parsed @param pos A ParsePosition object with index and error index will beinformation as setdescribed above. @return the parsed value or null if the parse fails @exception NullPointerException if text or pos is null.


Class DecimalFormatSymbols

This class represents the set of symbols (such as the decimal separator the grouping separator and so on) needed by DecimalFormat to format numbers. DecimalFormat creates for itself an instance of DecimalFormatSymbols from its locale data. If you need to change any of these symbols you can get the DecimalFormatSymbols object from your DecimalFormat and modify it. @see java.util.Locale @see DecimalFormat @version 1.30 0135 12/1903/0001 @author Mark Davis @author Alan Liu
Class DecimalFormatSymbols, constructor DecimalFormatSymbols(Locale)

Create a DecimalFormatSymbols object for the given locale. @exception NullPointerException if locale is null
Class DecimalFormatSymbols, String getCurrencySymbol()

ReturnReturns the stringcurrency denoting the localsymbol for the currency of these DecimalFormatSymbols in their locale.
Class DecimalFormatSymbols, String getInfinity()

Gets the characterstring used to represent infinity. Almost always left unchanged.
Class DecimalFormatSymbols, String getInternationalCurrencySymbol()

ReturnReturns the internationalISO string denoting the4217 currency code localof the currency of these DecimalFormatSymbols.
Class DecimalFormatSymbols, char getMonetaryDecimalSeparator()

ReturnReturns the monetary decimal separator.
Class DecimalFormatSymbols, String getNaN()

Gets the characterstring used to represent NaN"not a number". Almost always left unchanged.
Class DecimalFormatSymbols, void setCurrencySymbol(String)

SetSets the stringcurrency denoting the localsymbol for the currency of these DecimalFormatSymbols in their locale.
Class DecimalFormatSymbols, void setDecimalSeparator(char)

SetSets the character used for decimal sign. Different for French etc.
Class DecimalFormatSymbols, void setDigit(char)

SetSets the character used for a digit in a pattern.
Class DecimalFormatSymbols, void setGroupingSeparator(char)

SetSets the character used for thousands separator. Different for French etc.
Class DecimalFormatSymbols, void setInfinity(String)

SetSets the characterstring used to represent infinity. Almost always left unchanged.
Class DecimalFormatSymbols, void setInternationalCurrencySymbol(String)

SetSets the internationalISO string4217 denotingcurrency code of the currency of these DecimalFormatSymbols. If the currency code is valid (as defined by Currency.getInstance this also sets the currency attribute to the corresponding Currency instance and the currency symbol attribute to the currency's symbol in the DecimalFormatSymbols' locale. If the currency code is not valid then the localcurrency attribute is set to null and the currency symbol attribute is not modified. @see #setCurrency @see #setCurrencySymbol
Class DecimalFormatSymbols, void setMinusSign(char)

SetSets the character used to represent minus sign. If no explicit negative format is specified one is formed by prefixing minusSign to the positive format.
Class DecimalFormatSymbols, void setMonetaryDecimalSeparator(char)

SetSets the monetary decimal separator.
Class DecimalFormatSymbols, void setNaN(String)

SetSets the characterstring used to represent NaN"not a number". Almost always left unchanged.
Class DecimalFormatSymbols, void setPatternSeparator(char)

SetSets the character used to separate positive and negative subpatterns in a pattern.
Class DecimalFormatSymbols, void setPerMill(char)

SetSets the character used for mille percent sign. Different for Arabic etc.
Class DecimalFormatSymbols, void setPercent(char)

SetSets the character used for percent sign. Different for Arabic etc.
Class DecimalFormatSymbols, void setZeroDigit(char)

SetSets the character used for zero. Different for Arabic etc.

Class FieldPosition

FieldPosition is a simple class used by Format and its subclasses to identify fields in formatted output. Fields arecan be identified byin constantstwo ways:

FieldPosition keeps track of the position of the field within the formatted output with two indices: the index of the first character of the field and the index of the last character of the field.

One version of the format method in the various Format classes requires a FieldPosition object as an argument. You use this format method to perform partial formatting or to get information about the formatted output (such as the position of a field).

If you are interested in the positions of all attributes in the formatted string use the Format method formatToCharacterIterator. @version 1.16 0118 12/1903/0001 @author Mark Davis @see java.text.Format


Class Format

Format is an abstract base class for formatting locale-sensitive information such as dates messages and numbers.

Format defines the programming interface for formatting locale-sensitive objects into Strings (the format method) and for parsing Strings back into objects (the parseObject method). Any

StringGenerally formatteda byformat's formatparseObject is guaranteedmethod tomust be parseable by parseObject.able If formatting is unsuccessful because theto parse any string formatted by its Format object cannot format the type of objectmethod. specifiedHowever formatthere throws anmay be IllegalArgumentException.exceptional Otherwise if therecases where this is somethingnot illformedpossible. about the objectFor example a format returns the Unicodemethod replacement charactermight create \\uFFFD.two If there isadjacent integer numbers with no matchseparator when parsingin between parseObject(String)and throws ain this ParseExceptioncase andthe parseObject(String ParsePosition) leaves thecould not ParsePositiontell indexwhich member unchanged and returnsdigits belong to which nullnumber.

Subclassing:

The Java 2 platform provides three concretespecialized subclasses of Format-- DateFormat MessageFormat and NumberFormat--for formatting dates messages and numbers respectively.

Concrete subclasses must implement these twothree methods:

  1. format(Object obj StringBuffer toAppendTo FieldPosition pos)
  2. parseObjectformatToCharacterIterator(Object obj)
  3. parseObject(String source ParsePosition pos)
These general methods allow polymorphic parsing and formatting of objects and are used for example 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 that does not take a ParsePosition argument should throw ParseException when no text in the required format is at the beginning of the input text.

Most subclasses will also implement the following twofactory methods:

  1. getInstance for getting a useful format object appropriate for the current locale
  2. getInstance(Locale) for getting a useful format object appropriate for the specified locale
In addition some subclasses may also choose to implement other getXxxxInstance methods for more specialized control. For example the NumberFormat class provides getPercentInstance and getCurrencyInstance methods for getting specialized number formatters.

Subclasses of Format that allow programmers to create objects for locales (with getInstance(Locale) for example) must also implement the following class method:

 public static Locale[] getAvailableLocales() 

And finally subclasses may define a set of constants to identify the various fields in the formatted output. These constants are used to create a FieldPosition object which identifies what information is contained in the field and its position in the formatted result. These constants should be named item_FIELD where item identifies the field. For examples of these constants see ERA_FIELD and its friends in DateFormat

Synchronization

Formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see java.text.ParsePosition @see java.text.FieldPosition @see java.text.NumberFormat @see java.text.DateFormat @see java.text.MessageFormat @version 1.28 0131 12/1903/0001 @author Mark Davis

Class Format, Object clone()

OverridesCreates Cloneableand returns a copy of this object. @return a clone of this instance.
Class Format, String format(Object)

Formats an object to produce a string. SubclassesThis will override the StringBufferis equivalent to
versionStringBuffe ofFieldPosition) format}(obj new StringBuffer() new FieldPosition(0)).toString();
@param obj The object to format @return Formatted string. @exception IllegalArgumentException whenif the Format cannot format the type ofgiven object. @see MessageFormat @see java.text.Format#format(Object StringBuffer FieldPosition)
Class Format, StringBuffer format(Object, StringBuffer, FieldPosition)

Formats an object to produceand aappends string.the Subclasses will implement for particular objectresulting text to a given string suchbuffer. as:If the StringBufferpos formatargument (Numberidentifies obj StringBuffera field toAppendTo)used Number parseby the (Stringformat str)then These general routines allow polymorphic parsingits indices are set to the beginning and formattingend for objects such as the MessageFormatof the first such field encountered. @param obj The object to format @param toAppendTo where the text is to be appended @param pos OnA input:FieldPosition an alignmentidentifying a field if desired. On output: the offsets ofin the alignmentformatted field.text @return the valuestring buffer passed in as toAppendTo (thiswith allows chaining asformatted text appended with@exception StringBuffer.append())NullPointerException if toAppendTo or pos is null @exception IllegalArgumentException whenif the Format cannot format the given object. @see MessageFormat @see java.text.FieldPosition
Class Format, Object parseObject(String)

Parses atext from the beginning of the given string to produce an object. The method may not use the entire text of the given string. @param source A String whose beginning should be parsed. @return An Object parsed from the string. @exception ParseException if the beginning of the specified string iscannot be invalidparsed.
Class Format, Object parseObject(String, ParsePosition)

Parses text from a string to produce an object. Subclasses will typically implement for particular object such as:

String formatThe method attempts (Numberto obj);parse String formattext starting (longat obj);the String formatindex given (doubleby obj);pos. Number parseIf parsing (Stringsucceeds str);then the @paramindex statusof Input-Outputpos parameter.is Beforeupdated calling setto the status.index toafter the offset you wantlast to startcharacter used (parsing at in thedoes not necessarily source.use After callingall characters status.indexup isto the end of the text you parsed.string) If error occurs indexand the parsed object is unchangedreturned. When parsing leading whitespace is discarded (with successful parse) while trailing whitespace is leftThe asupdated is.pos Example:can Parsingbe "_12_xy"used (whereto _ represents aindicate the starting space)point for a number with index == 0 will result in the number 12 with status.indexnext updatedcall to 3 (just before the secondthis space)method. Parsing a secondIf time will result in a ParseException sincean error occurs then the index of "xy"pos is not a numberchanged and leavethe error index at 3. Subclasses will typically supply specificof parsepos methods that return different typesis set to the index of values. Since methodsthe can'tcharacter overload on return types these will typicallywhere the error occurred and null is bereturned. named@param "parse"source whileA thisString polymorphic method will alwayspart of which should be called parseObjectparsed. Any parse method that does not take a status should throw@param ParseException whenpos A noParsePosition text in the required format is at the start positionobject with index and error index information as described above. @return An Object parsed from the string. In case of error returns null. @seeexception java.textNullPointerException if pos is null.ParsePosition


Class MessageFormat

MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

MessageFormat takes a set of objects formats them then inserts the formatted strings into the pattern at the appropriate places.

Note: MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). The factory methods aren't necessary because MessageFormat itself doesn't require any compleximplement setup forlocale specific abehavior. givenAny locale. In factspecific MessageFormatbehavior doesn'tis implement any locale specific behavior atdefined by the pattern that you all.provide It just needs to be set up onas well as the subformats used for inserted aarguments. sentence

Patterns by sentenceand Their basis.Interpretation

MessageFormat Here are some examples of usageuses patterns of the following form:
 Object[]MessageFormatPattern: argumentsString =MessageFormatPattern FormatElement String FormatElement: { newArgumentIndex Integer(7)} new{ Date(System.currentTimeMillis())