Java Platform 1.2

java.text
Class DecimalFormat

java.lang.Object
  |
  +--java.text.Format
        |
        +--java.text.NumberFormat
              |
              +--java.text.DecimalFormat

public class DecimalFormat
extends NumberFormat

DecimalFormat is a concrete subclass of NumberFormat for formatting decimal numbers. This class allows for a variety of parameters, and localization to Western, Arabic, or Indic numbers.

Normally, you get the proper NumberFormat for a specific locale (including the default locale) using one of NumberFormat's factory methods such as getInstance. You may then modify it from there (after testing to make sure it is a DecimalFormat, of course!)

Either the prefixes or the suffixes must be different for the parse to distinguish positive from negative. Parsing will be unreliable if the digits, thousands or decimal separators are the same, or if any of them occur in the prefixes or suffixes.

Special cases:

NaN is formatted as a single character, typically \\uFFFD.

+/-Infinity is formatted as a single character, typically \\u221E, plus the positive and negative pre/suffixes.

Note: this class is designed for common users; for very large or small numbers, use a format that can express exponential values.

Example:

 // normally we would have a GUI with a menu for this
 Locale[] locales = NumberFormat.getAvailableLocales();

 double myNumber = -1234.56;
 NumberFormat form;

 // just for fun, we print out a number with the locale number, currency
 // and percent format for each locale we can.
 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
            continue;
         }
         System.out.print(locales[i].getDisplayName());
         switch (j) {
         default:
             form = NumberFormat.getInstance(locales[i]); break;
         case 1:
             form = NumberFormat.getCurrencyInstance(locales[i]); break;
         case 0:
             form = NumberFormat.getPercentInstance(locales[i]); break;
         }
         try {
             System.out.print(": " + ((DecimalFormat)form).toPattern()
                          + " -> " + form.format(myNumber));
         } catch (IllegalArgumentException iae) { }
         try {
             System.out.println(" -> " + form.parse(form.format(myNumber)));
         } catch (ParseException pe) { }
     }
 }
 
The following shows the structure of the pattern.
 pattern    := subpattern{;subpattern}
 subpattern := {prefix}integer{.fraction}{suffix}

 prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
 suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
 integer    := '#'* '0'* '0'
 fraction   := '0'* '#'*

 Notation:
  X*       0 or more instances of X
  (X | Y)  either X or Y.
  X..Y     any character from X up to Y, inclusive.
  S - T    characters in S, except those in T
 
The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers. (In both cases, ',' can occur inside the integer portion--it is just too messy to indicate in BNF.)

Here are the special characters used in the parts of the subpattern, with notes on their usage.

 Symbol Meaning
 0      a digit
 #      a digit, zero shows as absent
 .      placeholder for decimal separator
 ,      placeholder for grouping separator.
 E      separates mantissa and exponent for exponential formats.
 ;      separates formats.
 -      default negative prefix.
 %      multiply by 100 and show as percentage
 ? multiply by 1000 and show as per mille
 ¤ currency sign; replaced by currency symbol; if
        doubled, replaced by international currency symbol.
        If present in a pattern, the monetary decimal separator
        is used instead of the decimal separator.
 X      any other characters can be used in the prefix or suffix
 '      used to quote special characters in a prefix or suffix.
 

Notes

If there is no explicit negative subpattern, - is prefixed to the positive form. 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#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)".

The exponent character must be immediately followed by one or more digit characters. Example: "0.###E0". The number of digit characters after the exponent character gives the minimum exponent digit count; there is no maximum. Negative exponents are denoted using the same prefix and/or suffix specified for the number itself. The minimum number of integer digits is achieved by adjusting the exponent. The maximum number of integer digits, if any, specifies the exponent grouping. For example, 12345 is formatted using "##0.###E0" as "12.345E3".

Illegal patterns, such as "#.#.#" or mixing '_' and '*' in the same pattern, will cause an IllegalArgumentException to be thrown. From the message of IllegalArgumentException, you can find the place in the string where the error occurred.

The grouping separator is commonly used for thousands, but in some countries for ten-thousands. The interval is a constant number of digits between the grouping characters, such as 100,000,000 or 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 "#,##,###,####" == "######,####" == "##,####,####".

When calling DecimalFormat.parse(String, ParsePosition) and parsing fails, a null object will be returned. The unchanged parse position also reflects that an error has occurred during parsing. When calling the convenient method DecimalFormat.parse(String) and parsing fails, a ParseException will be thrown.

This class handles all Unicode characters that represent decimal digits. This set of characters is defined in the Unicode standard.

See Also:
Format, NumberFormat, ChoiceFormat, Serialized Form

Fields inherited from class java.text.NumberFormat
FRACTION_FIELD, INTEGER_FIELD
 
Constructor Summary
DecimalFormat()
          Create a DecimalFormat using the default pattern and symbols for the default locale.
DecimalFormat(String pattern)
          Create a DecimalFormat from the given pattern and the symbols for the default locale.
DecimalFormat(String pattern, DecimalFormatSymbols symbols)
          Create a DecimalFormat from the given pattern and symbols.
 
Method Summary
 void applyLocalizedPattern(String pattern)
          Apply the given pattern to this Format object.
 void applyPattern(String pattern)
          Apply the given pattern to this Format object.
 Object clone()
          Standard override; no change in semantics.
 boolean equals(Object obj)
          Overrides equals
 StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition)
           
 StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition)
           
 DecimalFormatSymbols getDecimalFormatSymbols()
          Returns the decimal format symbols, which is generally not changed by the programmer or user.
 int getGroupingSize()
          Return the grouping size.
 int getMultiplier()
          Get the multiplier for use in percent, permill, etc.
 String getNegativePrefix()
          Get the negative prefix.
 String getNegativeSuffix()
          Get the negative suffix.
 String getPositivePrefix()
          Get the positive prefix.
 String getPositiveSuffix()
          Get the positive suffix.
 int hashCode()
          Overrides hashCode
 boolean isDecimalSeparatorAlwaysShown()
          Allows you to get the behavior of the decimal separator with integers.
 Number parse(String text, ParsePosition parsePosition)
           
 void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols)
          Sets the decimal format symbols, which is generally not changed by the programmer or user.
 void setDecimalSeparatorAlwaysShown(boolean newValue)
          Allows you to set the behavior of the decimal separator with integers.
 void setGroupingSize(int newValue)
          Set the grouping size.
 void setMaximumFractionDigits(int newValue)
          Sets the maximum number of digits allowed in the fraction portion of a number.
 void setMaximumIntegerDigits(int newValue)
          Sets the maximum number of digits allowed in the integer portion of a number.
 void setMinimumFractionDigits(int newValue)
          Sets the minimum number of digits allowed in the fraction portion of a number.
 void setMinimumIntegerDigits(int newValue)
          Sets the minimum number of digits allowed in the integer portion of a number.
 void setMultiplier(int newValue)
          Set the multiplier for use in percent, permill, etc.
 void setNegativePrefix(String newValue)
          Set the negative prefix.
 void setNegativeSuffix(String newValue)
          Set the positive suffix.
 void setPositivePrefix(String newValue)
          Set the positive prefix.
 void setPositiveSuffix(String newValue)
          Set the positive suffix.
 String toLocalizedPattern()
          Synthesizes a localized pattern string that represents the current state of this Format object.
 String toPattern()
          Synthesizes a pattern string that represents the current state of this Format object.
 
Methods inherited from class java.text.NumberFormat
format, format, format, getAvailableLocales, getCurrencyInstance, getCurrencyInstance, getInstance, getInstance, getMaximumFractionDigits, getMaximumIntegerDigits, getMinimumFractionDigits, getMinimumIntegerDigits, getNumberInstance, getNumberInstance, getPercentInstance, getPercentInstance, isGroupingUsed, isParseIntegerOnly, parse, parseObject, setGroupingUsed, setParseIntegerOnly
 
Methods inherited from class java.text.Format
format, parseObject
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DecimalFormat

public DecimalFormat()
Create 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 Also:
NumberFormat.getInstance(), NumberFormat.getNumberInstance(), NumberFormat.getCurrencyInstance(), NumberFormat.getPercentInstance()

DecimalFormat

public DecimalFormat(String pattern)
Create a DecimalFormat from 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.

Parameters:
pattern - A non-localized pattern string.
Throws:
IllegalArgumentException - if the given pattern is invalid.
See Also:
NumberFormat.getInstance(), NumberFormat.getNumberInstance(), NumberFormat.getCurrencyInstance(), NumberFormat.getPercentInstance()

DecimalFormat

public DecimalFormat(String pattern,
                     DecimalFormatSymbols symbols)
Create a DecimalFormat from 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.

Parameters:
pattern - a non-localized pattern string
symbols - the set of symbols to be used
Throws:
IllegalArgumentException - if the given pattern is invalid
See Also:
NumberFormat.getInstance(), NumberFormat.getNumberInstance(), NumberFormat.getCurrencyInstance(), NumberFormat.getPercentInstance(), DecimalFormatSymbols
Method Detail

format

public StringBuffer format(double number,
                           StringBuffer result,
                           FieldPosition fieldPosition)
Overrides:
format in class NumberFormat

format

public StringBuffer format(long number,
                           StringBuffer result,
                           FieldPosition fieldPosition)
Overrides:
format in class NumberFormat

parse

public Number parse(String text,
                    ParsePosition parsePosition)
Overrides:
parse in class NumberFormat

getDecimalFormatSymbols

public DecimalFormatSymbols getDecimalFormatSymbols()
Returns the decimal format symbols, which is generally not changed by the programmer or user.
Returns:
desired DecimalFormatSymbols
See Also:
DecimalFormatSymbols

setDecimalFormatSymbols

public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols)
Sets the decimal format symbols, which is generally not changed by the programmer or user.
Parameters:
newSymbols - desired DecimalFormatSymbols
See Also:
DecimalFormatSymbols

getPositivePrefix

public String getPositivePrefix()
Get the positive prefix.

Examples: +123, $123, sFr123


setPositivePrefix

public void setPositivePrefix(String newValue)
Set the positive prefix.

Examples: +123, $123, sFr123


getNegativePrefix

public String getNegativePrefix()
Get the negative prefix.

Examples: -123, ($123) (with negative suffix), sFr-123


setNegativePrefix

public void setNegativePrefix(String newValue)
Set the negative prefix.

Examples: -123, ($123) (with negative suffix), sFr-123


getPositiveSuffix

public String getPositiveSuffix()
Get the positive suffix.

Example: 123%


setPositiveSuffix

public void setPositiveSuffix(String newValue)
Set the positive suffix.

Example: 123%


getNegativeSuffix

public String getNegativeSuffix()
Get the negative suffix.

Examples: -123%, ($123) (with positive suffixes)


setNegativeSuffix

public void setNegativeSuffix(String newValue)
Set the positive suffix.

Examples: 123%


getMultiplier

public int getMultiplier()
Get the multiplier for use in percent, permill, etc. For a percentage, set the suffixes to have "%" and the multiplier to be 100. (For Arabic, use arabic percent symbol). For a permill, set the suffixes to have "?" and the multiplier to be 1000.

Examples: with 100, 1.23 -> "123", and "123" -> 1.23


setMultiplier

public void setMultiplier(int newValue)
Set the multiplier for use in percent, permill, etc. For a percentage, set the suffixes to have "%" and the multiplier to be 100. (For Arabic, use arabic percent symbol). For a permill, set the suffixes to have "?" and the multiplier to be 1000.

Examples: with 100, 1.23 -> "123", and "123" -> 1.23


getGroupingSize

public int getGroupingSize()
Return the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3.
See Also:
setGroupingSize(int), NumberFormat.isGroupingUsed(), DecimalFormatSymbols.getGroupingSeparator()

setGroupingSize

public void setGroupingSize(int newValue)
Set the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3.
See Also:
getGroupingSize(), NumberFormat.setGroupingUsed(boolean), DecimalFormatSymbols.setGroupingSeparator(char)

isDecimalSeparatorAlwaysShown

public boolean isDecimalSeparatorAlwaysShown()
Allows you to get the behavior of the decimal separator with integers. (The decimal separator will always appear with decimals.)

Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345


setDecimalSeparatorAlwaysShown

public void setDecimalSeparatorAlwaysShown(boolean newValue)
Allows you to set the behavior of the decimal separator with integers. (The decimal separator will always appear with decimals.)

Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345


clone

public Object clone()
Standard override; no change in semantics.
Overrides:
clone in class NumberFormat

equals

public boolean equals(Object obj)
Overrides equals
Overrides:
equals in class NumberFormat

hashCode

public int hashCode()
Overrides hashCode
Overrides:
hashCode in class NumberFormat

toPattern

public String toPattern()
Synthesizes a pattern string that represents the current state of this Format object.
See Also:
applyPattern(java.lang.String)

toLocalizedPattern

public String toLocalizedPattern()
Synthesizes a localized pattern string that represents the current state of this Format object.
See Also:
applyPattern(java.lang.String)

applyPattern

public void applyPattern(String pattern)
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 parantheses.

In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern.


applyLocalizedPattern

public void applyLocalizedPattern(String pattern)
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 parantheses.

In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern.


setMaximumIntegerDigits

public void setMaximumIntegerDigits(int newValue)
Sets the maximum number of digits allowed in the integer portion of a number. This override limits the integer digit count to 309.
Overrides:
setMaximumIntegerDigits in class NumberFormat
See Also:
NumberFormat.setMaximumIntegerDigits(int)

setMinimumIntegerDigits

public void setMinimumIntegerDigits(int newValue)
Sets the minimum number of digits allowed in the integer portion of a number. This override limits the integer digit count to 309.
Overrides:
setMinimumIntegerDigits in class NumberFormat
See Also:
NumberFormat.setMinimumIntegerDigits(int)

setMaximumFractionDigits

public void setMaximumFractionDigits(int newValue)
Sets the maximum number of digits allowed in the fraction portion of a number. This override limits the fraction digit count to 340.
Overrides:
setMaximumFractionDigits in class NumberFormat
See Also:
NumberFormat.setMaximumFractionDigits(int)

setMinimumFractionDigits

public void setMinimumFractionDigits(int newValue)
Sets the minimum number of digits allowed in the fraction portion of a number. This override limits the fraction digit count to 340.
Overrides:
setMinimumFractionDigits in class NumberFormat
See Also:
NumberFormat.setMinimumFractionDigits(int)

Java Platform 1.2

Submit a bug or feature Version 1.2 of Java Platform API Specification
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1998 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.