Save This Page
Home » apache-harmony-6.0-src-r917296-snapshot » java » text » [javadoc | source]
java.text
public class: DecimalFormat [javadoc | source]
java.lang.Object
   java.text.Format
      java.text.NumberFormat
         java.text.DecimalFormat

All Implemented Interfaces:
    Cloneable, Serializable

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, or Indic digits. It also supports different flavors of numbers, including integers ("123"), fixed-point numbers ("123.4"), scientific notation ("1.23E4"), percentages ("12%"), and currency amounts ("$123"). All of these flavors can be easily localized.

This is an enhanced version of {@code DecimalFormat} that is based on the standard version in the RI. New or changed functionality is labeled NEW.

To obtain a NumberFormat for a specific locale (including the default locale), call one of {@code NumberFormat}'s factory methods such as {@code NumberFormat.getInstance}. Do not call the {@code DecimalFormat} constructors directly, unless you know what you are doing, since the NumberFormat factory methods may return subclasses other than {@code 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);
}
Example:
// Print out a number using the localized number, currency,
// and percent format for each locale
Locale[] locales = NumberFormat.getAvailableLocales();
double myNumber = -1234.56;
NumberFormat format;
for (int j = 0; j < 3; ++j) {
    System.out.println("FORMAT");
    for (int i = 0; i < locales.length; ++i) {
        if (locales[i].getCountry().length() == 0) {
            // Skip language-only locales
            continue;
        }
        System.out.print(locales[i].getDisplayName());
        switch (j) {
            case 0:
                format = NumberFormat.getInstance(locales[i]);
                break;
            case 1:
                format = NumberFormat.getCurrencyInstance(locales[i]);
                break;
            default:
                format = NumberFormat.getPercentInstance(locales[i]);
                break;
        }
        try {
            // Assume format is a DecimalFormat
            System.out.print(": "; + ((DecimalFormat)format).toPattern() + " -> "
                    + form.format(myNumber));
        } catch (Exception e) {
        }
        try {
            System.out.println(" -> " + format.parse(form.format(myNumber)));
        } catch (ParseException e) {
        }
    }
}

Patterns

A {@code DecimalFormat} consists of a pattern and a set of symbols. The pattern may be set directly using #applyPattern(String) , or indirectly using other API methods which manipulate aspects of the pattern, such as the minimum number of integer digits. The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods, the pattern and symbols are read from ICU's locale data.

Special Pattern Characters

Many characters in a pattern are taken literally; they are matched during parsing and are written out unchanged during formatting. On the other hand, special characters stand for other characters, strings, or classes of characters. For example, the '#' character is replaced by a localized digit. Often the replacement character is the same as the pattern character; in the U.S. locale, the ',' grouping character is replaced by ','. However, the replacement is still happening, and if the symbols are modified, the grouping character changes. Some special characters affect the behavior of the formatter by their presence; for example, if the percent character is seen, then the value is multiplied by 100 before being displayed.

To insert a special character in a pattern as a literal, that is, without any special meaning, the character must be quoted. There are some exceptions to this which are noted below.

The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters taken from this formatter's DecimalFormatSymbols object instead, and these characters lose their special status. Two exceptions are the currency sign and quote, which are not localized.

Symbol Location Localized? Meaning
{@code 0} Number Yes Digit.
{@code @} Number No NEW  Significant digit.
{@code #} Number Yes Digit, leading zeroes are not shown.
{@code .} Number Yes Decimal separator or monetary decimal separator.
{@code -} Number Yes Minus sign.
{@code ,} Number Yes Grouping separator.
{@code E} Number Yes Separates mantissa and exponent in scientific notation. Does not need to be quoted in prefix or suffix.
{@code +} Exponent Yes NEW  Prefix positive exponents with localized plus sign. Does not need to be quoted in prefix or suffix.
{@code ;} Subpattern boundary Yes Separates positive and negative subpatterns.
{@code %} Prefix or suffix Yes Multiply by 100 and show as percentage.
{@code \u2030} ({@code \u2030}) Prefix or suffix Yes Multiply by 1000 and show as per mille.
{@code ¤} ({@code \u00A4}) Prefix or suffix No 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.
{@code '} Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, {@code "'#'#"} formats 123 to {@code "#123"}. To create a single quote itself, use two in a row: {@code "# o''clock"}.
{@code *} Prefix or suffix boundary Yes NEW  Pad escape, precedes pad character.

A {@code DecimalFormat} pattern contains a postive and negative subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a prefix, a numeric part and a suffix. If there is no explicit negative subpattern, the negative subpattern is the localized minus sign prefixed to the positive 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 ignored in the negative subpattern. This means that "#,##0.0#;(#)" produces precisely the same result 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 #parse to be able to distinguish positive from negative values. Another example is that the decimal separator and thousands separator should be distinct characters, or parsing will be impossible.

The grouping separator is a character that separates clusters of integer digits to make large numbers more legible. It is commonly used for thousands, but in some locales it separates ten-thousands. The grouping size is the number of digits between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 0000". There are actually two different grouping sizes: One used for the least significant integer digits, the primary grouping size, and one used for all others, the secondary grouping size. In most locales these are the same, but sometimes they are different. For example, if the primary grouping interval is 3, and the secondary is 2, then this corresponds to the pattern "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a pattern contains multiple grouping separators, the interval between the last one and the end of the integer defines the primary grouping size, and the interval between the last two defines the secondary grouping size. All others are ignored, so "#,##,###,####", "###,###,####" and "##,#,###,####" produce the same result.

Illegal patterns, such as "#.#.#" or "#.###,###", will cause {@code DecimalFormat} to throw an IllegalArgumentException with a message that describes the problem.

Pattern BNF

pattern    := subpattern (';' subpattern)?
subpattern := prefix? number exponent? suffix?
number     := (integer ('.' fraction)?) | sigDigits
prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
integer    := '#'* '0'* '0'
fraction   := '0'* '#'*
sigDigits  := '#'* '@' '@'* '#'*
exponent   := 'E' '+'? '0'* '0'
padSpec    := '*' padChar
padChar    := '\\u0000'..'\\uFFFD' - quote

Notation:
  X*       0 or more instances of X
  X?       0 or 1 instances of X
  X|Y      either X or Y
  C..D     any character from C up to D, inclusive
  S-T      characters in S, except those in T
The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers.

Not indicated in the BNF syntax above:

Parsing

{@code DecimalFormat} parses all Unicode characters that represent decimal digits, as defined by Character#digit(int, int) . In addition, {@code DecimalFormat} also recognizes as digits the ten consecutive characters starting with the localized zero digit defined in the DecimalFormatSymbols object. During formatting, the DecimalFormatSymbols -based digits are written out.

During parsing, grouping separators are ignored.

If #parse(String, ParsePosition) fails to parse a string, it returns {@code null} and leaves the parse position unchanged.

Formatting

Formatting is guided by several parameters, all of which can be specified either using a pattern or using the API. The following description applies to formats that do not use scientific notation or significant digits.

Special Values

{@code NaN} is represented as a single character, typically {@code \uFFFD}. This character is determined by the DecimalFormatSymbols object. This is the only value for which the prefixes and suffixes are not used.

Infinity is represented as a single character, typically {@code \u221E}, with the positive or negative prefixes and suffixes applied. The infinity character is determined by the DecimalFormatSymbols object.

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 103. The mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0), but it does not need to be. {@code DecimalFormat} supports arbitrary mantissas. {@code DecimalFormat} can be instructed to use scientific notation through the API or through the pattern. 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".

NEW  Significant Digits

{@code DecimalFormat} has two ways of controlling how many digits are shown: (a) significant digit counts or (b) integer and fraction digit counts. Integer and fraction digit counts are described above. When a formatter uses significant digits counts, the number of integer and fraction digits is not specified directly, and the formatter settings for these counts are ignored. Instead, the formatter uses as many integer and fraction digits as required to display the specified number of significant digits.

Examples:
Pattern Minimum significant digits Maximum significant digits Number Output of format()
{@code @@@} 3 3 12345 {@code 12300}
{@code @@@} 3 3 0.12345 {@code 0.123}
{@code @@##} 2 4 3.14159 {@code 3.142}
{@code @@##} 2 4 1.23004 {@code 1.23}

NEW  Padding

{@code DecimalFormat} supports padding the result of {@code format} to a specific width. Padding may be specified either through the API or through the pattern syntax. In a pattern, the pad escape character followed by a single pad character causes padding to be parsed and formatted. The pad escape character is '*' in unlocalized patterns. For example, {@code "$*x#,##0.00"} formats 123 to {@code "$xx123.00"}, and 1234 to {@code "$1,234.00"}.

Synchronization

{@code DecimalFormat} objects are not synchronized. Multiple threads should not access one formatter concurrently.

Fields inherited from java.text.NumberFormat:
INTEGER_FIELD,  FRACTION_FIELD
Constructor:
 public DecimalFormat() 
 public DecimalFormat(String pattern) 
    Constructs a new {@code DecimalFormat} using the specified non-localized pattern and the {@code DecimalFormatSymbols} for the default Locale.
    Parameters:
    pattern - the non-localized pattern.
    Throws:
    IllegalArgumentException - if the pattern cannot be parsed.
 public DecimalFormat(String pattern,
    DecimalFormatSymbols value) 
    Constructs a new {@code DecimalFormat} using the specified non-localized pattern and {@code DecimalFormatSymbols}.
    Parameters:
    pattern - the non-localized pattern.
    value - the DecimalFormatSymbols.
    Throws:
    IllegalArgumentException - if the pattern cannot be parsed.
 DecimalFormat(String pattern,
    DecimalFormatSymbols value,
    DecimalFormat icuFormat) 
Method from java.text.DecimalFormat Summary:
applyLocalizedPattern,   applyPattern,   clone,   equals,   format,   format,   format,   formatToCharacterIterator,   getCurrency,   getDecimalFormatSymbols,   getGroupingSize,   getMultiplier,   getNegativePrefix,   getNegativeSuffix,   getPositivePrefix,   getPositiveSuffix,   getRoundingMode,   hashCode,   isDecimalSeparatorAlwaysShown,   isGroupingUsed,   isParseBigDecimal,   isParseIntegerOnly,   parse,   setCurrency,   setDecimalFormatSymbols,   setDecimalSeparatorAlwaysShown,   setGroupingSize,   setGroupingUsed,   setMaximumFractionDigits,   setMaximumIntegerDigits,   setMinimumFractionDigits,   setMinimumIntegerDigits,   setMultiplier,   setNegativePrefix,   setNegativeSuffix,   setParseBigDecimal,   setParseIntegerOnly,   setPositivePrefix,   setPositiveSuffix,   setRoundingMode,   toLocalizedPattern,   toPattern
Methods from java.text.NumberFormat:
clone,   equals,   format,   format,   format,   format,   format,   getAvailableLocales,   getCurrency,   getCurrencyInstance,   getCurrencyInstance,   getInstance,   getInstance,   getIntegerInstance,   getIntegerInstance,   getMaximumFractionDigits,   getMaximumIntegerDigits,   getMinimumFractionDigits,   getMinimumIntegerDigits,   getNumberInstance,   getNumberInstance,   getPercentInstance,   getPercentInstance,   getRoundingMode,   hashCode,   isGroupingUsed,   isParseIntegerOnly,   parse,   parse,   parseObject,   setCurrency,   setGroupingUsed,   setMaximumFractionDigits,   setMaximumIntegerDigits,   setMinimumFractionDigits,   setMinimumIntegerDigits,   setParseIntegerOnly,   setRoundingMode
Methods from java.text.Format:
clone,   convertPattern,   format,   format,   formatToCharacterIterator,   getInternalField,   parseObject,   parseObject,   upTo,   upToWithQuotes
Methods from java.lang.Object:
clone,   equals,   finalize,   getClass,   hashCode,   notify,   notifyAll,   toString,   wait,   wait,   wait
Method from java.text.DecimalFormat Detail:
 public  void applyLocalizedPattern(String pattern) 
    Changes the pattern of this decimal format to the specified pattern which uses localized pattern characters.
 public  void applyPattern(String pattern) 
    Changes the pattern of this decimal format to the specified pattern which uses non-localized pattern characters.
 public Object clone() 
    Returns a new instance of {@code DecimalFormat} with the same pattern and properties as this decimal format.
 public boolean equals(Object object) 
    Compares the specified object to this decimal format and indicates if they are equal. In order to be equal, {@code object} must be an instance of {@code DecimalFormat} with the same pattern and properties.
 public StringBuffer format(double value,
    StringBuffer buffer,
    FieldPosition position) 
    Formats the specified double value as a string using the pattern of this decimal format and appends the string to the specified string buffer.

    If the {@code field} member of {@code position} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

 public StringBuffer format(long value,
    StringBuffer buffer,
    FieldPosition position) 
    Formats the specified long value as a string using the pattern of this decimal format and appends the string to the specified string buffer.

    If the {@code field} member of {@code position} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

 public final StringBuffer format(Object number,
    StringBuffer toAppendTo,
    FieldPosition pos) 
    Formats the specified object as a string using the pattern of this decimal format and appends the string to the specified string buffer.

    If the {@code field} member of {@code position} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

 public AttributedCharacterIterator formatToCharacterIterator(Object object) 
    Formats the specified object using the rules of this decimal format and returns an {@code AttributedCharacterIterator} with the formatted number and attributes.
 public Currency getCurrency() 
    Returns the currency used by this decimal format.
 public DecimalFormatSymbols getDecimalFormatSymbols() 
    Returns the {@code DecimalFormatSymbols} used by this decimal format.
 public int getGroupingSize() 
    Returns the number of digits grouped together by the grouping separator. This only allows to get the primary grouping size. There is no API to get the secondary grouping size.
 public int getMultiplier() 
    Returns the multiplier which is applied to the number before formatting or after parsing.
 public String getNegativePrefix() 
    Returns the prefix which is formatted or parsed before a negative number.
 public String getNegativeSuffix() 
    Returns the suffix which is formatted or parsed after a negative number.
 public String getPositivePrefix() 
    Returns the prefix which is formatted or parsed before a positive number.
 public String getPositiveSuffix() 
    Returns the suffix which is formatted or parsed after a positive number.
 public RoundingMode getRoundingMode() 
    Get the RoundingMode of this DecimalFormat
 public int hashCode() 
 public boolean isDecimalSeparatorAlwaysShown() 
    Indicates whether the decimal separator is shown when there are no fractional digits.
 public boolean isGroupingUsed() 
    Indicates whether grouping will be used in this format.
 public boolean isParseBigDecimal() 
    This value indicates whether the return object of the parse operation is of type {@code BigDecimal}. This value defaults to {@code false}.
 public boolean isParseIntegerOnly() 
    Indicates whether parsing with this decimal format will only return numbers of type {@code java.lang.Integer}.
 public Number parse(String string,
    ParsePosition position) 
    Parses a {@code Long} or {@code Double} from the specified string starting at the index specified by {@code position}. If the string is successfully parsed then the index of the {@code ParsePosition} is updated to the index following the parsed text. On error, the index is unchanged and the error index of {@code ParsePosition} is set to the index where the error occurred.
 public  void setCurrency(Currency currency) 
    Sets the currency used by this decimal format. The min and max fraction digits remain the same.
 public  void setDecimalFormatSymbols(DecimalFormatSymbols value) 
    Sets the {@code DecimalFormatSymbols} used by this decimal format.
 public  void setDecimalSeparatorAlwaysShown(boolean value) 
    Sets whether the decimal separator is shown when there are no fractional digits.
 public  void setGroupingSize(int value) 
    Sets the number of digits grouped together by the grouping separator. This only allows to set the primary grouping size; the secondary grouping size can only be set with a pattern.
 public  void setGroupingUsed(boolean value) 
    Sets whether or not grouping will be used in this format. Grouping affects both parsing and formatting.
 public  void setMaximumFractionDigits(int value) 
    Sets the maximum number of fraction digits that are printed when formatting numbers other than {@code BigDecimal} and {@code BigInteger}. If the maximum is less than the number of fraction digits, the least significant digits are truncated. If the value passed is bigger than 340 then it is replaced by 340. If the value passed is negative then it is replaced by 0.
 public  void setMaximumIntegerDigits(int value) 
    Sets the maximum number of integer digits that are printed when formatting numbers other than {@code BigDecimal} and {@code BigInteger}. If the maximum is less than the number of integer digits, the most significant digits are truncated. If the value passed is bigger than 309 then it is replaced by 309. If the value passed is negative then it is replaced by 0.
 public  void setMinimumFractionDigits(int value) 
    Sets the minimum number of fraction digits that are printed when formatting numbers other than {@code BigDecimal} and {@code BigInteger}. If the value passed is bigger than 340 then it is replaced by 340. If the value passed is negative then it is replaced by 0.
 public  void setMinimumIntegerDigits(int value) 
    Sets the minimum number of integer digits that are printed when formatting numbers other than {@code BigDecimal} and {@code BigInteger}. If the value passed is bigger than 309 then it is replaced by 309. If the value passed is negative then it is replaced by 0.
 public  void setMultiplier(int value) 
    Sets the multiplier which is applied to the number before formatting or after parsing.
 public  void setNegativePrefix(String value) 
    Sets the prefix which is formatted or parsed before a negative number.
 public  void setNegativeSuffix(String value) 
    Sets the suffix which is formatted or parsed after a negative number.
 public  void setParseBigDecimal(boolean newValue) 
    Sets the behaviour of the parse method. If set to {@code true} then all the returned objects will be of type {@code BigDecimal}.
 public  void setParseIntegerOnly(boolean value) 
    Sets the flag that indicates whether numbers will be parsed as integers. When this decimal format is used for parsing and this value is set to {@code true}, then the resulting numbers will be of type {@code java.lang.Integer}. Special cases are NaN, positive and negative infinity, which are still returned as {@code java.lang.Double}.
 public  void setPositivePrefix(String value) 
    Sets the prefix which is formatted or parsed before a positive number.
 public  void setPositiveSuffix(String value) 
    Sets the suffix which is formatted or parsed after a positive number.
 public  void setRoundingMode(RoundingMode roundingMode) 
    Set the RoundingMode of this DecimalFormat
 public String toLocalizedPattern() 
    Returns the pattern of this decimal format using localized pattern characters.
 public String toPattern() 
    Returns the pattern of this decimal format using non-localized pattern characters.