DecimalFormat Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
<strong>[icu enhancement]</strong> ICU's replacement for java.text.DecimalFormat
.
[Android.Runtime.Register("android/icu/text/DecimalFormat", ApiSince=24, DoNotGenerateAcw=true)]
public class DecimalFormat : Android.Icu.Text.NumberFormat
[<Android.Runtime.Register("android/icu/text/DecimalFormat", ApiSince=24, DoNotGenerateAcw=true)>]
type DecimalFormat = class
inherit NumberFormat
- Inheritance
- Derived
- Attributes
Remarks
<strong>[icu enhancement]</strong> ICU's replacement for java.text.DecimalFormat
. Methods, fields, and other functionality specific to ICU are labeled '<strong>[icu]</strong>'.
<strong>IMPORTANT:</strong> 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. <hr>
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.
<strong>NOTE:</strong> 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 android.icu.number.
<h3>Example Usage</h3>
Customize settings on a DecimalFormat instance from the NumberFormat factory:
<blockquote>
NumberFormat f = NumberFormat.getInstance(loc);
if (f instanceof DecimalFormat) {
((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
((DecimalFormat) f).setMinimumGroupingDigits(2);
}
</blockquote>
Quick and dirty print out a number using the localized number, currency, and percent format for each locale:
<blockquote>
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();
}
</blockquote>
<h3>Properties and Symbols</h3>
A DecimalFormat object encapsulates a set of <em>properties</em> and a set of <em>symbols</em>. 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.
<h3>Rounding</h3>
DecimalFormat provides three main strategies to specify the position at which numbers should be rounded:
<ol> <li><strong>Magnitude:</strong> Display a fixed number of fraction digits; this is the most common form. <li><strong>Increment:</strong> Round numbers to the closest multiple of a certain increment, such as 0.05. This is common in currencies. <li><strong>Significant Digits:</strong> Round numbers such that a fixed number of nonzero digits are shown. This is most common in scientific notation. </ol>
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 <em>rounding mode</em> 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.
<h3>Pattern Strings</h3>
A <em>pattern string</em> 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.
<h4>Pattern String BNF</h4>
The following BNF is used when parsing the pattern string into property values:
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:
<ul> <li>The grouping separator ',' can occur inside the integer and sigDigits elements, between any two pattern characters of that element, as long as the integer or sigDigits element is not followed by the exponent element. <li>Two grouping intervals are recognized: That between the decimal point and the first grouping symbol, and that between the first and second grouping symbols. These intervals are identical in most locales, but in some locales they differ. For example, the pattern "#,##,###" formats the number 123456789 as "12,34,56,789". <li>The pad specifier padSpec
may appear before the prefix, after the prefix, before the suffix, after the suffix, or not at all. <li>In place of '0', the digits '1' through '9' may be used to indicate a rounding increment. </ul>
<h3>Parsing</h3>
DecimalFormat aims to be able to parse anything that it can output as a formatted string.
There are two primary parse modes: <em>lenient</em> and <em>strict</em>. 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.text.ParseException
.
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:
android.icu.impl.number.Parse.DEBUGGING = true;
df.parse("123.45", ppos);
android.icu.impl.number.Parse.DEBUGGING = false;
<h3>Thread Safety and Best Practices</h3>
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 documentation for android.icu.text.DecimalFormat
.
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
DecimalFormat() |
Creates a DecimalFormat based on the number pattern and symbols for the default locale. |
DecimalFormat(IntPtr, JniHandleOwnership) | |
DecimalFormat(String, DecimalFormatSymbols, CurrencyPluralInfo, NumberFormatStyles) |
Creates a DecimalFormat based on the given pattern and symbols, with additional control over the behavior of currency. |
DecimalFormat(String, DecimalFormatSymbols) |
Creates a DecimalFormat based on the given pattern and symbols. |
DecimalFormat(String) |
Creates a DecimalFormat based on the given pattern, using symbols for the default locale. |
Fields
Accountingcurrencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify currency style of format which uses currency symbol to represent currency for accounting, for example: "($3. (Inherited from NumberFormat) |
Cashcurrencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify currency cash style of format which uses currency ISO code to represent currency, for example: "NT$3" instead of "NT$3. (Inherited from NumberFormat) |
Currencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify general currency style of format. (Inherited from NumberFormat) |
FractionField |
Obsolete.
Field constant used to construct a FieldPosition object. (Inherited from NumberFormat) |
IntegerField |
Obsolete.
Field constant used to construct a FieldPosition object. (Inherited from NumberFormat) |
Integerstyle |
Obsolete.
<strong>[icu]</strong> Constant to specify a integer number style format. (Inherited from NumberFormat) |
Isocurrencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify currency style of format which uses currency ISO code to represent currency, for example: "USD3. (Inherited from NumberFormat) |
MinimumGroupingDigitsAuto |
<strong>[icu]</strong> Constant for |
MinimumGroupingDigitsMin2 |
<strong>[icu]</strong> Constant for |
Numberstyle |
Obsolete.
<strong>[icu]</strong> Constant to specify normal number style of format. (Inherited from NumberFormat) |
PadAfterPrefix |
Obsolete.
<strong>[icu]</strong> Constant for |
PadAfterSuffix |
Obsolete.
<strong>[icu]</strong> Constant for |
PadBeforePrefix |
Obsolete.
<strong>[icu]</strong> Constant for |
PadBeforeSuffix |
Obsolete.
<strong>[icu]</strong> Constant for |
Percentstyle |
Obsolete.
<strong>[icu]</strong> Constant to specify a style of format to display percent. (Inherited from NumberFormat) |
Pluralcurrencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify currency style of format which uses currency long name with plural format to represent currency, for example, "3. (Inherited from NumberFormat) |
Scientificstyle |
Obsolete.
<strong>[icu]</strong> Constant to specify a style of format to display scientific number. (Inherited from NumberFormat) |
Standardcurrencystyle |
Obsolete.
<strong>[icu]</strong> Constant to specify currency style of format which uses currency symbol to represent currency, for example "$3. (Inherited from NumberFormat) |
Properties
Class |
Returns the runtime class of this |
Currency |
Returns the |
CurrencyPluralInfo |
<strong>[icu]</strong> Returns the current instance of CurrencyPluralInfo. -or- <strong>[icu]</strong> Sets a custom instance of CurrencyPluralInfo. |
CurrencyUsage | |
DecimalFormatSymbols |
Returns a copy of the decimal format symbols used by this formatter. -or- Sets the decimal format symbols used by this formatter. |
DecimalPatternMatchRequired |
<strong>[icu]</strong> Returns whether the presence of a decimal point must match the pattern. -or- <strong>[icu]</strong> <strong>Parsing:</strong> This method is used to either <em>require</em> or <em>forbid</em> the presence of a decimal point in the string being parsed (disabled by default). |
DecimalSeparatorAlwaysShown |
Returns whether the decimal separator is shown on integers. -or- <strong>Separators:</strong> Sets whether the decimal separator (a period in <em>en-US</em>) is shown on integers. |
ExponentSignAlwaysShown |
<strong>[icu]</strong> Returns whether the sign (plus or minus) is always printed in scientific notation. -or- <strong>[icu]</strong> <strong>Scientific Notation:</strong> Sets whether the sign (plus or minus) is always to be shown in the exponent in scientific notation. |
FormatWidth |
Returns the minimum number of characters in formatted output. -or- <strong>Padding:</strong> Sets the minimum width of the string output by the formatting pipeline. |
GroupingSize |
Returns the primary grouping size in use. -or- <strong>Grouping:</strong> Sets the primary grouping size (distance between grouping separators) used when formatting large numbers. |
GroupingUsed |
Returns true if grouping is used in this format. -or- Sets whether or not grouping will be used in this format. (Inherited from NumberFormat) |
Handle |
The handle to the underlying Android instance. (Inherited from Object) |
JniIdentityHashCode | (Inherited from Object) |
JniPeerMembers | |
MathContext |
<strong>[icu]</strong> Returns the |
MathContextICU |
<strong>[icu]</strong> Returns the |
MaximumFractionDigits |
Returns the maximum number of digits allowed in the fraction portion of a number. -or- Sets the maximum number of digits allowed in the fraction portion of a number. (Inherited from NumberFormat) |
MaximumIntegerDigits |
Returns the maximum number of digits allowed in the integer portion of a number. -or- Sets the maximum number of digits allowed in the integer portion of a number. (Inherited from NumberFormat) |
MaximumSignificantDigits |
<strong>[icu]</strong> Returns the effective maximum number of significant digits displayed. -or- <strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Sets the maximum number of significant digits to be displayed. |
MinimumExponentDigits |
<strong>[icu]</strong> Returns the minimum number of digits printed in the exponent in scientific notation. -or- <strong>[icu]</strong> <strong>Scientific Notation:</strong> Sets the minimum number of digits to be printed in the exponent. |
MinimumFractionDigits |
Returns the minimum number of digits allowed in the fraction portion of a number. -or- Sets the minimum number of digits allowed in the fraction portion of a number. (Inherited from NumberFormat) |
MinimumGroupingDigits |
<strong>[icu]</strong> Returns the minimum number of digits before grouping is triggered. -or- <strong>[icu]</strong> Sets the minimum number of digits that must be before the first grouping separator in order for the grouping separator to be printed. |
MinimumIntegerDigits |
Returns the minimum number of digits allowed in the integer portion of a number. -or- Sets the minimum number of digits allowed in the integer portion of a number. (Inherited from NumberFormat) |
MinimumSignificantDigits |
<strong>[icu]</strong> Returns the effective minimum number of significant digits displayed. -or- <strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Sets the minimum number of significant digits to be displayed. |
Multiplier |
Returns the multiplier being applied to numbers before they are formatted. -or- Sets a number that will be used to multiply all numbers prior to formatting. |
NegativePrefix |
<strong>Affixes:</strong> Gets the negative prefix string currently being used to format numbers. -or- <strong>Affixes:</strong> Sets the string to prepend to negative numbers. |
NegativeSuffix |
<strong>Affixes:</strong> Gets the negative suffix string currently being used to format numbers. -or- <strong>Affixes:</strong> Sets the string to append to negative numbers. |
PadCharacter |
<strong>[icu]</strong> Returns the character used for padding. -or- <strong>[icu]</strong> <strong>Padding:</strong> Sets the character used to pad numbers that are narrower than
the width specified in |
PadPosition |
<strong>[icu]</strong> Returns the position used for padding. -or- <strong>[icu]</strong> <strong>Padding:</strong> Sets the position where to insert the pad character when
narrower than the width specified in |
ParseBigDecimal |
Returns whether |
ParseCaseSensitive |
<strong>[icu]</strong> Returns whether to force case (uppercase/lowercase) to match when parsing. -or- <strong>[icu]</strong> Specifies whether parsing should require cases to match in affixes, exponent separators, and currency codes. |
ParseIntegerOnly |
Returns true if this format will parse numbers as integers only. -or- Sets whether to ignore the fraction part of a number when parsing (defaults to false). (Inherited from NumberFormat) |
ParseMaxDigits |
Always returns 1000, the default prior to ICU 59. -or- This member is deprecated. |
ParseNoExponent |
<strong>[icu]</strong> Returns whether to ignore exponents when parsing. -or- <strong>[icu]</strong> Specifies whether to stop parsing when an exponent separator is encountered. |
ParseStrict |
<strong>[icu]</strong> Returns whether strict parsing is in effect. -or- <strong>[icu]</strong> Sets whether strict parsing is in effect. (Inherited from NumberFormat) |
PeerReference | (Inherited from Object) |
PositivePrefix |
<strong>Affixes:</strong> Gets the positive prefix string currently being used to format numbers. -or- <strong>Affixes:</strong> Sets the string to prepend to positive numbers. |
PositiveSuffix |
<strong>Affixes:</strong> Gets the positive suffix string currently being used to format numbers. -or- <strong>Affixes:</strong> Sets the string to append to positive numbers. |
RoundingIncrement |
<strong>[icu]</strong> Returns the increment to which numbers are being rounded. -or- <strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Sets an increment, or interval, to which numbers are rounded. |
RoundingMode |
Returns the rounding mode used in this NumberFormat. -or- Set the rounding mode used in this NumberFormat. (Inherited from NumberFormat) |
ScientificNotation |
<strong>[icu]</strong> Returns whether scientific (exponential) notation is enabled on this formatter. -or- <strong>[icu]</strong> <strong>Scientific Notation:</strong> Sets whether this formatter should print in scientific (exponential) notation. |
SecondaryGroupingSize |
<strong>[icu]</strong> Returns the secondary grouping size in use. -or- <strong>[icu]</strong> <strong>Grouping:</strong> Sets the secondary grouping size (distance between grouping separators after the first separator) used when formatting large numbers. |
SignAlwaysShown |
<strong>[icu]</strong> Returns whether the sign is being shown on positive numbers. -or- Sets whether to always shown the plus sign ('+' in <em>en</em>) on positive numbers. |
ThresholdClass | |
ThresholdType |
Methods
ApplyLocalizedPattern(String) |
Converts the given string to standard notation and then parses it using |
ApplyPattern(String) |
Parses the given pattern string and overwrites the settings specified in the pattern string. |
AreSignificantDigitsUsed() |
<strong>[icu]</strong> Returns whether significant digits are being used in rounding. |
Clone() |
Creates and returns a copy of this object. (Inherited from _Format) |
Dispose() | (Inherited from Object) |
Dispose(Boolean) | (Inherited from Object) |
Equals(Object) |
Indicates whether some other object is "equal to" this one. (Inherited from Object) |
Format(BigDecimal, StringBuffer, FieldPosition) |
To be added |
Format(BigDecimal, StringBuffer, FieldPosition) |
To be added |
Format(BigDecimal) |
Convenience method to format a BigDecimal. (Inherited from NumberFormat) |
Format(BigDecimal) |
<strong>[icu]</strong> Convenience method to format an ICU BigDecimal. (Inherited from NumberFormat) |
Format(BigInteger, StringBuffer, FieldPosition) |
To be added |
Format(BigInteger) |
<strong>[icu]</strong> Convenience method to format a BigInteger. (Inherited from NumberFormat) |
Format(CurrencyAmount, StringBuffer, FieldPosition) |
<strong>[icu]</strong> Formats a CurrencyAmount. (Inherited from NumberFormat) |
Format(CurrencyAmount) |
<strong>[icu]</strong> Convenience method to format a CurrencyAmount. (Inherited from NumberFormat) |
Format(Double, StringBuffer, FieldPosition) |
To be added |
Format(Double) |
Specialization of format. (Inherited from NumberFormat) |
Format(Int64, StringBuffer, FieldPosition) |
To be added |
Format(Int64) |
Specialization of format. (Inherited from NumberFormat) |
Format(Object, StringBuffer, FieldPosition) |
Formats a number and appends the resulting text to the given string buffer. (Inherited from NumberFormat) |
Format(Object) |
Formats an object to produce a string. (Inherited from _Format) |
FormatToCharacterIterator(Object) |
Formats an Object producing an |
GetContext(DisplayContext+Type) | (Inherited from NumberFormat) |
GetHashCode() |
Returns a hash code value for the object. (Inherited from Object) |
JavaFinalize() |
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. (Inherited from Object) |
Notify() |
Wakes up a single thread that is waiting on this object's monitor. (Inherited from Object) |
NotifyAll() |
Wakes up all threads that are waiting on this object's monitor. (Inherited from Object) |
Parse(String, ParsePosition) |
To be added |
Parse(String) |
Parses text from the beginning of the given string to produce a number. (Inherited from NumberFormat) |
ParseCurrency(ICharSequence, ParsePosition) |
Parses text from the given string as a CurrencyAmount. (Inherited from NumberFormat) |
ParseCurrency(String, ParsePosition) |
Parses text from the given string as a CurrencyAmount. (Inherited from NumberFormat) |
ParseObject(String, ParsePosition) |
Parses text from a string to produce a number. (Inherited from NumberFormat) |
ParseObject(String) |
Parses text from the beginning of the given string to produce an object. (Inherited from _Format) |
SetContext(DisplayContext) |
<strong>[icu]</strong> Set a particular DisplayContext value in the formatter, such as CAPITALIZATION_FOR_STANDALONE. (Inherited from NumberFormat) |
SetHandle(IntPtr, JniHandleOwnership) |
Sets the Handle property. (Inherited from Object) |
SetRoundingIncrement(BigDecimal) |
<strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Overload of |
SetRoundingIncrement(Double) |
<strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Overload of |
SetSignificantDigitsUsed(Boolean) |
<strong>[icu]</strong> <strong>Rounding and Digit Limits:</strong> Sets whether significant digits are to be used in rounding. |
ToArray<T>() | (Inherited from Object) |
ToLocalizedPattern() |
Calls |
ToPattern() |
Serializes this formatter object to a decimal format pattern string. |
ToString() |
Returns a string representation of the object. (Inherited from Object) |
UnregisterFromRuntime() | (Inherited from Object) |
Wait() |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>. (Inherited from Object) |
Wait(Int64, Int32) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Wait(Int64) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
JavaCast<TResult>(IJavaObject) |
Performs an Android runtime-checked type conversion. |
JavaCast<TResult>(IJavaObject) | |
GetJniTypeName(IJavaPeerable) |
Gets the JNI name of the type of the instance |
JavaAs<TResult>(IJavaPeerable) |
Try to coerce |
TryJavaCast<TResult>(IJavaPeerable, TResult) |
Try to coerce |