ICU Enhancement
This class is ICU's replacement for java..
ICU
Methods, fields, and other functionality specific to ICU are labeled 'ICU'.
Important Note
New users are strongly encouraged to see if
NumberFormatter fits their use case. Although not deprecated, this
class, DecimalFormat, is only provided for java.text.DecimalFormat compatibility.
DecimalFormat is the primary
concrete subclass of NumberFormat. 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 supports different flavors of numbers, including integers ("123"), fixed-point
numbers ("123.4"), scientific notation ("1.23E4"), percentages ("12%"), and currency amounts
("$123.00", "USD123.00", "123.00 US dollars"). All of these flavors can be easily localized.
To obtain a number formatter for a specific locale (including the default locale), call one of
NumberFormat's factory methods such as NumberFormat#getInstance. Do not call
DecimalFormat constructors directly unless you know what you are doing.
DecimalFormat aims to comply with the specification UTS #35. Read the specification for more information on how all the properties in DecimalFormat fit together.
Note
Starting in ICU 60, there is a new set of APIs for localized number formatting that are designed to be an improvement over DecimalFormat. New users are discouraged from using DecimalFormat. For more information, see the package com.ibm.icu.number.
Customize settings on a DecimalFormat instance from the NumberFormat factory:
NumberFormat f = NumberFormat.getInstance(loc);
if (f instanceof DecimalFormat) {
((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
((DecimalFormat) f).setMinimumGroupingDigits(2);
}
Quick and dirty print out a number using the localized number, currency, and percent format for each locale:
for (ULocale uloc : ULocale.getAvailableLocales()) {
System.out.print(uloc + ":\t");
System.out.print(NumberFormat.getInstance(uloc).format(1.23));
System.out.print("\t");
System.out.print(NumberFormat.getCurrencyInstance(uloc).format(1.23));
System.out.print("\t");
System.out.print(NumberFormat.getPercentInstance(uloc).format(1.23));
System.out.println();
}
A DecimalFormat object encapsulates a set of properties and a set of symbols. Grouping size, rounding mode, and affixes are examples of properties. Locale digits and the characters used for grouping and decimal separators are examples of symbols.
To set a custom set of symbols, use setDecimalFormatSymbols. Use the various other
setters in this class to set custom values for the properties.
DecimalFormat provides three main strategies to specify the position at which numbers should be rounded:
It is not possible to specify more than one rounding strategy. For example, setting a rounding increment in conjunction with significant digits results in undefined behavior.
It is also possible to specify the rounding mode to use. The default rounding mode is
"half even", which rounds numbers to their closest increment, with ties broken in favor of
trailing numbers being even. For more information, see setRoundingMode and the ICU
User Guide.
A pattern string is a way to serialize some of the available properties for decimal
formatting. However, not all properties are capable of being serialized into a pattern string;
see applyPattern for more information.
Most users should not need to interface with pattern strings directly.
ICU DecimalFormat aims to follow the specification for pattern strings in UTS #35. Refer to that specification for more information on pattern string syntax.
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:
padSpec may appear before the prefix, after the prefix,
before the suffix, after the suffix, or not at all.
DecimalFormat aims to be able to parse anything that it can output as a formatted string.
There are two primary parse modes: lenient and strict. Lenient mode should
be used if the goal is to parse user input to a number; strict mode should be used if the goal is
validation. The default is lenient mode. For more information, see setParseStrict.
DecimalFormat parses all Unicode characters that represent decimal digits, as
defined by UCharacter#digit. In addition, 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 output.
Grouping separators are ignored in lenient mode (default). In strict mode, grouping separators must match the locale-specified grouping sizes.
When using parseCurrency, all currencies are accepted, not just the currency
currently set in the formatter. In addition, the formatter is able to parse every currency style
format for a particular locale no matter which style the formatter is constructed with. For
example, a formatter instance gotten from NumberFormat.getInstance(ULocale,
NumberFormat.CURRENCYSTYLE) can parse both "USD1.00" and "3.00 US dollars".
Whitespace characters (lenient mode) and control characters (lenient and strict mode), collectively called "ignorables", do not need to match in identity or quantity between the pattern string and the input string. For example, the pattern "# %" matches "35 %" (with a single space), "35%" (with no space), "35 %" (with a non-breaking space), and "35 %" (with multiple spaces). Arbitrary ignorables are also allowed at boundaries between the parts of the number: prefix, number, exponent separator, and suffix. Ignorable whitespace characters are those having the Unicode "blank" property for regular expressions, defined in UTS #18 Annex C, which is "horizontal" whitespace, like spaces and tabs, but not "vertical" whitespace, like line breaks. Ignorable control characters are those in the Unicode set [:Default_Ignorable_Code_Point:].
If parse(String, ParsePosition) fails to parse a string, it returns null
and leaves the parse position unchanged. The convenience method parse(String) indicates
parse failure by throwing a java..
Under the hood, a state table parsing engine is used. To debug a parsing failure during development, use the following pattern to print details about the state table transitions:
com.ibm.icu.impl.number.Parse.DEBUGGING = true;
df.parse("123.45", ppos);
com.ibm.icu.impl.number.Parse.DEBUGGING = false;
Starting with ICU 59, instances of DecimalFormat are thread-safe.
Under the hood, DecimalFormat maintains an immutable formatter object that is rebuilt whenever any of the property setters are called. It is therefore best practice to call property setters only during construction and not when formatting numbers online.
java.text.Format , NumberFormat
| Modifier and Type | Class and Description |
|---|---|
| public static interface | DecimalFormat.PropertySetter
Deprecated
This API is ICU internal only.
|
| Modifier and Type | Field and Description |
|---|---|
| pack-priv transient volatile NumberParserImpl | |
| pack-priv transient volatile DecimalFormatProperties | exportedProperties
The effective properties as exported from the formatter object. |
| pack-priv transient volatile LocalizedNumberFormatter | formatter
The pre-computed formatter object. |
| private transient int | |
| public static final int | |
| public static final int | |
| public static final int | |
| public static final int | |
| public static final int | |
| public static final int | |
| pack-priv transient volatile NumberParserImpl | |
| pack-priv transient DecimalFormatProperties | properties
The property bag corresponding to user-specified settings and settings from the pattern string. |
| private final int | serialVersionOnStream
One non-transient field such that deserialization can determine the version of the class.
|
| private static final long | serialVersionUID
New serialization in ICU 59: declare different version from ICU 58.
|
| pack-priv transient volatile DecimalFormatSymbols | symbols
The symbols for the current locale. |
| Access | Constructor and Description |
|---|---|
| public | DecimalFormat()
Creates a DecimalFormat based on the number pattern and symbols for the default locale. |
| public | DecimalFormat(String
A pattern string such as "#,##0.00" conforming to UTS
#35. pattern)Creates a DecimalFormat based on the given pattern, using symbols for the default locale. |
| public | DecimalFormat(String
A pattern string such as "#,##0.00" conforming to UTS
#35. pattern, DecimalFormatSymbols The set of symbols to be used. symbols)Creates a DecimalFormat based on the given pattern and symbols. |
| public | DecimalFormat(String
a non-localized pattern string pattern, DecimalFormatSymbols the set of symbols to be used symbols, CurrencyPluralInfo the information used for currency plural format, including currency plural
patterns and plural rules. infoInput, int the decimal formatting style, it is one of the following values:
NumberFormat.NUMBERSTYLE; NumberFormat.CURRENCYSTYLE; NumberFormat.PERCENTSTYLE;
NumberFormat.SCIENTIFICSTYLE; NumberFormat.INTEGERSTYLE; NumberFormat.ISOCURRENCYSTYLE;
NumberFormat.PLURALCURRENCYSTYLE; style)Creates a DecimalFormat based on the given pattern and symbols, with additional control over the behavior of currency. |
| pack-priv | DecimalFormat(String pattern, DecimalFormatSymbols symbols, int choice)
Package-private constructor used by NumberFormat. |
| Modifier and Type | Method and Description |
|---|---|
| public synchronized void | applyLocalizedPattern(String
The pattern string in localized notation. localizedPattern)Converts the given string to standard notation and then parses it using |
| public synchronized void | applyPattern(String pattern)
Parses the given pattern string and overwrites the settings specified in the pattern string. |
| public synchronized boolean | |
| public Object | |
| public synchronized boolean | equals(Object
the object to compare against obj)Overrides com. |
| pack-priv static void | fieldPositionHelper(DecimalQuantity dq, FormattedStringBuilder string, FieldPosition fieldPosition, int offset)
Deprecated
as a consequence of
DecimalQuantity being deprecated.
|
| public StringBuffer | format(double number, StringBuffer result, FieldPosition fieldPosition)
Implements abstract com. |
| public StringBuffer | format(long number, StringBuffer result, FieldPosition fieldPosition)
Implements abstract com. |
| public StringBuffer | format(BigInteger number, StringBuffer result, FieldPosition fieldPosition)
Implements abstract com. ICU |
| public StringBuffer | format(BigDecimal number, StringBuffer result, FieldPosition fieldPosition)
Implements abstract com. ICU |
| public StringBuffer | format(BigDecimal number, StringBuffer result, FieldPosition fieldPosition)
Implements abstract com. ICU |
| public StringBuffer | format(CurrencyAmount currAmt, StringBuffer result, FieldPosition fieldPosition)
Overrides com. ICU |
| public AttributedCharacterIterator | formatToCharacterIterator(Object
The object to format obj)Overrides java. AttributedCharacterIterator.
|
| public synchronized Currency | getCurrency()
Overrides com. |
| pack-priv NumberParserImpl | |
| public synchronized CurrencyPluralInfo | |
| public synchronized Currency. | |
| public synchronized DecimalFormatSymbols | Returns: desired DecimalFormatSymbolsReturns a copy of the decimal format symbols used by this formatter. |
| private static DecimalFormatSymbols | |
| public PluralRules. | |
| public synchronized int | |
| public synchronized int | |
| public synchronized MathContext | |
| public synchronized MathContext | |
| public synchronized int | getMaximumFractionDigits()
Overrides com. |
| public synchronized int | getMaximumIntegerDigits()
Overrides com. |
| public synchronized int | |
| public synchronized byte | |
| public synchronized int | getMinimumFractionDigits()
Overrides com. |
| public synchronized int | |
| public synchronized int | getMinimumIntegerDigits()
Overrides com. |
| public synchronized int | |
| public synchronized int | |
| public synchronized String | Returns: The string being prepended to negative numbers.Affixes: Gets the negative prefix string currently being used to format numbers. |
| public synchronized String | Returns: The string being appended to negative numbers.Affixes: Gets the negative suffix string currently being used to format numbers. |
| public synchronized char | |
| public synchronized int | |
| public int | getParseMaxDigits()
Deprecated
Setting max parse digits has no effect since ICU4J 59.
Always returns 1000, the default prior to ICU 59.
|
| pack-priv NumberParserImpl | |
| public synchronized String | Returns: The string being prepended to positive numbers.Affixes: Gets the positive prefix string currently being used to format numbers. |
| public synchronized String | Returns: The string being appended to positive numbers.Affixes: Gets the positive suffix string currently being used to format numbers. |
| public synchronized BigDecimal | |
| public synchronized int | getRoundingMode()
Returns the rounding mode being used to round numbers.
|
| public synchronized int | |
| public synchronized int | hashCode()
Overrides com. |
| public synchronized boolean | |
| public synchronized boolean | |
| public synchronized boolean | |
| public synchronized boolean | isGroupingUsed()
Overrides com. |
| public synchronized boolean | |
| public synchronized boolean | |
| public synchronized boolean | isParseIntegerOnly()
Returns true if this format will parse numbers as integers only.
|
| public synchronized boolean | |
| public synchronized boolean | |
| public synchronized boolean | |
| public synchronized boolean | |
| public Number | parse(String text, ParsePosition parsePosition)
Implements abstract com. |
| public CurrencyAmount | parseCurrency(CharSequence
the text to parse text, ParsePosition input-output position; on input, the position within
text to match; must have 0 <= pos.getIndex() < text.length();
on output, the position after the last matched character. If
the parse fails, the position in unchanged upon output. parsePosition)Overrides com. |
| private void | readObject(ObjectInputStream ois)
Custom serialization: re-create object from serialized property bag and symbols.
|
| pack-priv void | |
| private Number | safeConvertBigDecimal(BigDecimal number)
Converts a java.math.BigDecimal to a com.ibm.icu.math.BigDecimal with fallback for numbers outside of the range supported by com.ibm.icu.math.BigDecimal. |
| public synchronized void | setCurrency(Currency
The currency to use. currency)Overrides com. |
| public synchronized void | setCurrencyPluralInfo(CurrencyPluralInfo
The CurrencyPluralInfo to use when printing currency long names. newInfo)ICU |
| public synchronized void | setCurrencyUsage(Currency.
The strategy to use when rounding in the current currency. usageICU |
| public synchronized void | setDecimalFormatSymbols(DecimalFormatSymbols
desired DecimalFormatSymbols newSymbols)Sets the decimal format symbols used by this formatter. |
| public synchronized void | setDecimalPatternMatchRequired(boolean
true to either require or forbid the decimal point according to the pattern; false
to disable this feature. value)ICU |
| public synchronized void | setDecimalSeparatorAlwaysShown(boolean
true to always show the decimal separator; false to show it only when there is a
fraction part of the number. value)Separators: Sets whether the decimal separator (a period in en-US) is shown on integers. |
| public synchronized void | setExponentSignAlwaysShown(boolean
true to always shown the sign in the exponent; false to show it for
negatives but not positives. expSignAlways)ICU |
| public synchronized void | setFormatWidth(int
The minimum number of characters in the output. width)Padding: Sets the minimum width of the string output by the formatting pipeline. |
| public synchronized void | setGroupingSize(int
The grouping size to use. width)Grouping: Sets the primary grouping size (distance between grouping separators) used when formatting large numbers. |
| public synchronized void | setGroupingUsed(boolean
true to enable grouping separators; false to disable them. enabled)
Grouping: Sets whether grouping is to be used when formatting numbers.
|
| public synchronized void | |
| public synchronized void | |
| public synchronized void | setMaximumFractionDigits(int
The maximum number of integer digits after the decimal separator. value)Overrides com. |
| public synchronized void | setMaximumIntegerDigits(int
The maximum number of digits before the decimal separator. value)Overrides com. |
| public synchronized void | |
| public synchronized void | |
| public synchronized void | setMinimumFractionDigits(int
The minimum number of integer digits after the decimal separator. value)Overrides com. |
| public synchronized void | |
| public synchronized void | setMinimumIntegerDigits(int
The minimum number of digits before the decimal separator. value)Overrides com. |
| public synchronized void | |
| public synchronized void | setMultiplier(int
The number by which all numbers passed to multiplier)format will be multiplied.Sets a number that will be used to multiply all numbers prior to formatting. |
| public synchronized void | setNegativePrefix(String
The literal string to prepend to negative numbers. prefix)Affixes: Sets the string to prepend to negative numbers. |
| public synchronized void | setNegativeSuffix(String
The literal string to append to negative numbers. suffix)Affixes: Sets the string to append to negative numbers. |
| public synchronized void | |
| public synchronized void | |
| public synchronized void | setParseBigDecimal(boolean value)
Whether to make |
| public synchronized void | setParseCaseSensitive(boolean
true to force case (uppercase/lowercase) to match when parsing; false to ignore
case and perform case folding. value)ICU |
| public synchronized void | setParseIntegerOnly(boolean
true to ignore fractional parts of numbers when parsing; false to
consume fractional parts. parseIntegerOnly)Overrides com. |
| public void | setParseMaxDigits(int
Prior to ICU 59, the maximum number of digits in the output number after
exponential notation is applied. maxDigits)
Deprecated
Setting max parse digits has no effect since ICU4J 59.
|
| public synchronized void | setParseNoExponent(boolean
true to prevent exponents from being parsed; false to allow them to be parsed. value)ICU |
| public synchronized void | setParseStrict(boolean
True to enable strict parsing. Default is false. parseStrict)Overrides com. ICU |
| public synchronized void | setParseStrictMode(DecimalFormatProperties.
Deprecated
This API is ICU internal only.
Android libcore uses this internal method to set ParseMode#JAVA_COMPATIBILITY.
|
| public synchronized void | setPositivePrefix(String
The literal string to prepend to positive numbers. prefix)Affixes: Sets the string to prepend to positive numbers. |
| public synchronized void | setPositiveSuffix(String
The literal string to append to positive numbers. suffix)Affixes: Sets the string to append to positive numbers. |
| public synchronized void | |
| pack-priv void | setPropertiesFromPattern(String
The pattern string to parse. pattern, int Whether to leave out rounding information (minFrac, maxFrac, and rounding
increment) when parsing the pattern. This may be desirable if a custom rounding mode, such
as CurrencyUsage, is to be used instead. One of ignoreRounding)PatternStringParser#IGNORE_ROUNDING_ALWAYS, PatternStringParser#IGNORE_ROUNDING_IF_CURRENCY,
or PatternStringParser#IGNORE_ROUNDING_NEVER.Updates the property bag with settings from the given pattern. |
| public synchronized void | |
| public synchronized void | |
| public synchronized void | |
| public synchronized void | setRoundingMode(int
The integer constant rounding mode to use when formatting numbers. roundingMode)Overrides com. RoundingMode used to round
numbers.
|
| public synchronized void | setScientificNotation(boolean
true to enable scientific notation; false to disable it. useScientific)ICU |
| public synchronized void | |
| public synchronized void | setSignAlwaysShown(boolean
true to always show a sign; false to hide the sign on positive numbers and zero. value)Sets whether to always shown the plus sign ('+' in en) on positive numbers. |
| public synchronized void | setSignificantDigitsUsed(boolean
true to enable significant digit rounding; false to disable it. useSignificantDigits)ICU |
| public synchronized String | Returns: A decimal format pattern string in localized notation.Calls |
| public LocalizedNumberFormatter | Returns: An instance ofLocalizedNumberFormatter with the same behavior as this instance of
DecimalFormat.Converts this DecimalFormat to a NumberFormatter. |
| public synchronized String | Returns: A decimal format pattern string.Serializes this formatter object to a decimal format pattern string. |
| public String | toString()
Overrides java. |
| private synchronized void | writeObject(ObjectOutputStream oos)
Custom serialization: save property bag and symbols; the formatter object can be re-created
from just that amount of information.
|