CompactNumberFormat is a concrete subclass of NumberFormat
that formats a decimal number in a localized compact form.
Compact number formatting is designed for an environment with limited space.
For example, displaying the formatted number 7M instead of 7,000,000.00 in the US locale. The CompactNumberFormat class is defined by LDML's specification for
Compact Number Formats.
NumberFormat#getCompactNumberInstance()
to obtain a format for the default locale with
SHORT style.
NumberFormat#getCompactNumberInstance(Locale, Style)
to obtain a format for a different locale
and to control the Style.
CompactNumberFormat constructors, for example, CompactNumberFormat(decimalPattern, symbols, compactPatterns), to obtain a
CompactNumberFormat with further customization.
If a standard compact format for a given locale and style is desired, it is recommended to use one of the
NumberFormat factory methods listed above. To use an instance method
defined by CompactNumberFormat, the NumberFormat returned by
these factory methods should be type checked before converted to CompactNumberFormat.
If the installed locale-sensitive service implementation does not support
the given Locale, the parent locale chain will be looked up, and
a Locale used that is supported.
NumberFormat#getCompactNumberInstance(Locale, Style), a
compact form can be retrieved with either a SHORT or LONG style.
For example, a SHORT style compact number instance in
the US locale formats 10000 as "10K". However, a LONG style instance in
the same locale formats 10000 as "10 thousand".
NumberFormat compactFormat = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); compactFormat.format(1000); // returns "1K" compactFormat.parse("1K"); // returns 1000
setMinimumFractionDigits(int)
method to include the fractional part.
The number 1000.0 or 1000 is formatted as "1K"
not "1.00K" (in the US locale). For this
reason, the patterns provided for formatting contain only the minimum
integer digits, prefix and/or suffix, but no fractional part.
For example, patterns used are {"", "", "", 0K, 00K, ...}. If the pattern
selected for formatting a number is "0" (special pattern),
either explicit or defaulted, then the general number formatting provided by
DecimalFormat
for the specified locale is used.
CompactNumberFormat provides rounding modes defined in
java.math.RoundingMode for formatting. By default, it uses
RoundingMode.HALF_EVEN .
true by using
setGroupingUsed(boolean). The parsing of the fractional part
depends on the isParseIntegerOnly(). For example, if the
parse integer only is set to true, then the fractional part is skipped.
The compactPatterns in CompactNumberFormat(decimalPattern, symbols, compactPatterns) are represented
as a series of strings, where each string is a pattern that is used to format a range of numbers.
An example of the SHORT styled compact number patterns
for the US locale is {"", "", "", "0K",
"00K", "000K", "0M", "00M", "000M", "0B", "00B", "000B", "0T", "00T", "000T"},
ranging from 100 to 1014.
There can be any number of patterns and they are
strictly index based starting from the range 100.
For example, in the above patterns, the pattern at index 3
("0K") is used for formatting a number in the range: 1000 <= number < 10000,
index 4 ("00K") for formatting a number the range: 10000 <=
number < 100000, and so forth.
In most locales, patterns with the range
100-102 are empty
strings, which implicitly means a special pattern "0".
A special pattern "0" is used for any range which does not contain
a compact pattern. This special pattern can appear explicitly for any specific
range, or considered as a default pattern for an empty string.
';',
for example, "0K;-0K". Each subpattern has a prefix,
minimum integer digits, and suffix. The negative subpattern
is optional, if absent, then the positive subpattern prefixed with the
minus sign '-' (U+002D HYPHEN-MINUS) is used as the negative
subpattern. That is, "0K" alone is equivalent to "0K;-0K".
If there is an explicit negative subpattern, it serves only to specify
the negative prefix and suffix. The number of minimum integer digits,
and other characteristics are all the same as the positive pattern.
That means that "0K;-00K" produces precisely the same behavior
as "0K;-0K". In lenient parsing
mode, loose matching of the minus sign pattern is enabled, following the
LDML’s
loose matching specification.
' (U+0027)
unless noted otherwise, if they are to appear in the prefix or suffix
as literals. For example, 0क'.'.
CompactNumberFormat support patterns for both singular and plural
compact forms. For the plural form, the Pattern should consist
of PluralPattern(s) separated by a space ' ' (U+0020) that are enumerated
within a pair of curly brackets '{' (U+007B) and '}' (U+007D).
In this format, each PluralPattern consists of its count,
followed by a single colon ':' (U+003A) and a SimplePattern.
As a space is reserved for separating subsequent PluralPatterns, it must
be quoted to be used literally in either the prefix or suffix.
For example, while the pattern representing millions (106
) in the US locale can be specified as the SimplePattern: "0 Million", for the
German locale it can be specified as the PluralPattern:
"{one:0' 'Million other:0' 'Millionen}".
A compact pattern has the following syntax, with count
following LDML's
Language Plural Rules:
Pattern:
SimplePattern
'{' PluralPattern [' ' PluralPattern]optional '}'
SimplePattern:
PositivePattern
PositivePattern [; NegativePattern]optional
PluralPattern:
Count:SimplePattern
Count:
"zero" / "one" / "two" / "few" / "many" / "other"
PositivePattern:
Prefixoptional MinimumInteger Suffixoptional
NegativePattern:
Prefixoptional MinimumInteger Suffixoptional
Prefix:
Any characters except the special pattern characters
Suffix:
Any characters except the special pattern characters
MinimumInteger:
0
0 MinimumInteger
NumberFormat.Style , NumberFormat, DecimalFormat, Locale
| Modifier and Type | Class and Description |
|---|---|
| private class | CompactNumberFormat.
Abstraction of affix or number (represented by zeros) patterns for each "count" tag. |
| Modifier and Type | Field and Description |
|---|---|
| private String[] | compactPatterns
The patterns for compact form of numbers for this
|
| private static final String | |
| private static final Pattern | |
| private static final char | |
| private static final char | |
| private transient DecimalFormat | decimalFormat
A |
| private final String | decimalPattern
The decimal pattern which is used for formatting the numbers matching special pattern "0". |
| private transient DecimalFormat | defaultDecimalFormat
A |
| private static final char | |
| private transient DigitList | |
| private transient List | divisors
List of divisors of this formatter's compact number patterns. |
| private static final String | |
| private static final Pattern | |
| private static final char | |
| private byte | groupingSize
The number of digits between grouping separators in the integer portion of a compact number. |
| private static final char | |
| private static final String | |
| private static final String | |
| private static final String | |
| private transient List | |
| private transient List | negativePrefixPatterns
List of negative prefix patterns of this formatter's compact number patterns. |
| private transient List | |
| private transient List | negativeSuffixPatterns
List of negative suffix patterns of this formatter's compact number patterns. |
| private transient Pattern | numberPattern
RegEx to parse number part of a compact number text |
| private boolean | parseBigDecimal
Returns whether the |
| private boolean | parseStrict
True if this |
| private static final char | |
| private static final char | |
| private transient List | placeHolderPatterns
List of place holders that represent minimum integer digits at each index for each count. |
| private String | pluralRules
The |
| private static final Pattern | |
| private static final Pattern | PLURALS
Process the series of compact patterns to compute the series of prefixes, suffixes and their respective divisor value. |
| private transient List | |
| private transient List | positivePrefixPatterns
List of positive prefix patterns of this formatter's compact number patterns. |
| private transient List | |
| private transient List | positiveSuffixPatterns
List of positive suffix patterns of this formatter's compact number patterns. |
| private static final char | |
| private static final int | RANGE_MULTIPLIER
Multiplier for compact pattern range. |
| private static final String | |
| private static final Pattern | |
| private RoundingMode | roundingMode
The |
| private transient Map | rulesMap
The map for plural rules that maps LDML defined tags (e.g. "one") to its rule. |
| private static final char | |
| private static final long | |
| private static final String | SPECIAL_PATTERN
Special pattern used for compact numbers |
| private static final int | |
| private static final int | |
| private static final int | |
| private DecimalFormatSymbols | symbols
The |
| private static final String | |
| private static final Pattern | |
| private static final char |
| Access | Constructor and Description |
|---|---|
| public | CompactNumberFormat(String
a decimal pattern
for general number formatting decimalPattern, DecimalFormatSymbols the set of symbols to be used symbols, String[] an array of
compact number patterns compactPatterns)Creates a |
| public | CompactNumberFormat(String
a decimal pattern
for general number formatting decimalPattern, DecimalFormatSymbols the set of symbols to be used symbols, String[] an array of
compact number patterns compactPatterns, String a String designating plural rules which associate
the pluralRules)Count keyword, such as "one", and the
actual integer number. Its syntax is defined in Unicode Consortium's
Plural rules syntaxCreates a |
| Modifier and Type | Method and Description |
|---|---|
| private void | append(Format.
the resulting string, where the text is to be appended result,the text to append string, Format.notified of the locations of sub fields delegate,a list of positions)FieldPosition in the given
stringAppends the |
| private void | appendPrefix(Format.
the resulting string, where the prefix is to be appended result,prefix to append prefix, Format.notified of the locations of
delegateNumberFormat.Field.SIGN and
NumberFormat.Field.PREFIX fieldsAppends the |
| private void | appendSuffix(Format.
the resulting string, where the suffix is to be appended result,suffix to append suffix, Format.notified of the locations of
delegateNumberFormat.Field.SIGN and
NumberFormat.Field.SUFFIX fieldsAppends |
| private void | applyPattern(String count, String
the compact pattern to be processed pattern, int index in the array of compact patterns index)Process a compact pattern at a specific |
| private Map | |
| private boolean | |
| public CompactNumberFormat | Returns: a clone of this instanceOverrides java. Creates and returns a copy of this |
| private Number | Returns: divisor value for the number matching the compact pattern at givenpatternIndexstring of 0s in compact pattern minIntDigits, int index of matched compact pattern patternIndex)Computes the divisor using minimum integer digits and matched pattern index. |
| private Number | Returns: the multiplier matching the prefix and suffix; -1 otherwisethe string to parse text, ParsePosition the parsePosition, String ParsePosition object representing the
index and error index of the parse stringprefix extracted which needs to be matched to
obtain the multiplier matchedPrefix, boolean[] upon return contains boolean status flags indicating
whether the value is positive status, boolean based on the prefix parsed; whether the number is positive gotPositive, boolean based on the prefix parsed; whether the number is negative gotNegative, double num)Computes multiplier by matching the given |
| private Number | Returns: the resulting valueparsed value number, boolean[] boolean status flags indicating whether the
value is infinite and whether it is positive status, boolean whether the parsed number is Long.MIN gotLongMin)Negate the parsed value if the positive status flag is false and the value is not a Long.MIN |
| public boolean | Returns: true if this is equal to the otherCompactNumberFormatthe object to compare with obj)Overrides java. Compares the specified object with this |
| private static double | Returns: resulting double valueMatch result expr, double value to examine in double input)Evaluates the left operand value. |
| private String | Returns: an expanded affixa compact number pattern affix pattern)Expands an affix |
| private void | |
| public final StringBuffer | Returns: theStringBuffer passed in as toAppendTothe number to format number, StringBuffer the toAppendTo, FieldPosition StringBuffer to which the formatted
text is to be appendedkeeps track on the position of the field within
the returned string. For example, for formatting
a number fieldPosition)123456789 in the
US locale,
if the given fieldPosition is
NumberFormat#INTEGER_FIELD, the begin
index and end index of fieldPosition
will be set to 0 and 3, respectively for the
output string 123M. Similarly, positions
of the prefix and the suffix fields can be
obtained using NumberFormat.
and NumberFormat. respectively.Overrides java. Formats a number to produce a string representing its compact form. |
| pack-priv Format. | format(Object number, Format.
Overrides java.
|
| public StringBuffer | Returns: theStringBuffer passed in as resultthe double number to format number, StringBuffer where the text is to be appended result, FieldPosition keeps track on the position of the field within
the returned string. For example, to format
a number fieldPosition)1234567.89 in the
US locale
if the given fieldPosition is
NumberFormat#INTEGER_FIELD, the begin
index and end index of fieldPosition
will be set to 0 and 1, respectively for the
output string 1M. Similarly, positions
of the prefix and the suffix fields can be
obtained using NumberFormat.
and NumberFormat. respectively.Implements abstract java. Formats a double to produce a string representing its compact form. |
| pack-priv Format. | format(double number, Format.
Overrides java.
|
| private Format. | |
| public StringBuffer | Returns: theStringBuffer passed in as resultthe long number to format number, StringBuffer where the text is to be appended result, FieldPosition keeps track on the position of the field within
the returned string. For example, to format
a number fieldPosition)123456789 in the
US locale,
if the given fieldPosition is
NumberFormat#INTEGER_FIELD, the begin
index and end index of fieldPosition
will be set to 0 and 3, respectively for the
output string 123M. Similarly, positions
of the prefix and the suffix fields can be
obtained using NumberFormat.
and NumberFormat. respectively.Implements abstract java. Formats a long to produce a string representing its compact form. |
| pack-priv Format. | format(long number, Format.
Overrides java.
|
| private Format. | |
| private Format. | Returns: theStringBuf passed in as resultthe BigDecimal number to format number, Format.where the text is to be appended result,keeps track on the position of the field within
the returned string. For example, to format
a number fieldPosition)1234567.89 in the
US locale,
if the given fieldPosition is
NumberFormat#INTEGER_FIELD, the begin
index and end index of fieldPosition
will be set to 0 and 1, respectively for the
output string 1M. Similarly, positions
of the prefix and the suffix fields can be
obtained using NumberFormat.
and NumberFormat. respectively.Formats a BigDecimal to produce a string representing its compact form. |
| private Format. | |
| private Format. | Returns: theStringBuf passed in as resultthe BigInteger number to format number, Format.where the text is to be appended result,keeps track on the position of the field within
the returned string. For example, to format
a number fieldPosition)123456789 in the
US locale,
if the given fieldPosition is
NumberFormat#INTEGER_FIELD, the begin index
and end index of fieldPosition will be set
to 0 and 3, respectively for the output string
123M. Similarly, positions of the
prefix and the suffix fields can be obtained
using NumberFormat. and
NumberFormat. respectively.Formats a BigInteger to produce a string representing its compact form. |
| private Format. | format(BigInteger number, Format.
|
| public AttributedCharacterIterator | Returns: anAttributedCharacterIterator describing the
formatted valueThe object to format obj)Overrides java. Formats an Object producing an |
| private Number | Returns: parsed resultparsed number component number, boolean whether the parsed number contains decimal gotDouble, boolean whether the parsed number is Long.MIN gotLongMin, boolean[] boolean status flags indicating whether the
value is infinite and whether it is positive status, Number compact number multiplier cnfMultiplier)Returns the parsed result by multiplying the parsed number with the multiplier representing the prefix and suffix. |
| private String | getAffix(boolean isExpanded, boolean isPrefix, boolean isNegative, int compactDataIndex, double val)
Obtain the designated affix from the appropriate list of affixes, based on the given arguments. |
| private List | Returns: a list ofFieldPositionthe pattern to be parsed for pattern, NumberFormat.FieldPositionwhether a PREFIX or SUFFIX field fieldReturns a list of |
| public int | |
| private double | |
| private String | Returns: LDML "count" taginput number in double type input)Returns LDML's tag from the plurals rules |
| public RoundingMode | Returns: theRoundingMode used for this
CompactNumberFormatOverrides java. Gets the |
| public int | Returns: the hash code for thisCompactNumberFormatOverrides java. Returns the hash code for this |
| public boolean | Returns: true if grouping is used;
false otherwiseOverrides java. Returns true if grouping is used in this format. |
| public boolean | Returns: true if the parse method returns BigDecimal;
false otherwiseReturns whether the |
| public boolean | Returns: true if compact numbers should be parsed as integers
only; false otherwiseOverrides java. Returns true if this format parses only an integer from the number component of a compact number. |
| public boolean | isStrict()
Overrides java. Returns |
| private boolean | matchAffix(String text, int position, String affix, String defaultAffix, String matchedAffix)
Attempts to match the given |
| private static boolean | |
| private boolean | |
| public Number | Returns: the parsed value, ornull if the parse failsthe string to be parsed text, ParsePosition a pos)ParsePosition object with index and error
index information as described aboveImplements abstract java. Parses text from the beginning of the given string to produce a |
| private double | Returns: the numberinput text to be parsed text, int starting position position)Parse the number part in the input text into a number |
| private void | |
| private void | readObject(ObjectInputStream
the stream inStream)Hides java. Reconstitutes this |
| private static boolean | Returns: boolean to indicate whether the relation satisfies or not. If the relation is '=', true if any of the possible value/range satisfies. If the relation is '!=', none of the possible value/range should satisfy to return true.relation string, e.g, "n = 1, 3..5", or "n != 1, 3..5" relation, double value to examine in double input)Checks if the input value satisfies the relation. |
| private int | Returns: index of matched compact pattern; -1 if no compact patterns specifiednumber to be formatted number)Select the index of the matched compact number pattern for
the given |
| private int | Returns: index of matched compact pattern; -1 if no compact patterns specifiednumber to be formatted number)Select the index of the matched compact number
pattern for the given |
| public void | |
| public void | setGroupingUsed(boolean
true if grouping is used;
false otherwiseOverrides java. Sets whether or not grouping will be used in this format. |
| public void | setMaximumFractionDigits(int
the maximum number of fraction digits to be shown. newValue)Overrides java. Sets the maximum number of digits allowed in the fraction portion of a number during formatting. |
| public void | setMaximumIntegerDigits(int
the maximum number of integer digits to be shown. newValue)Overrides java. Sets the maximum number of digits allowed in the integer portion of a number during formatting. |
| public void | setMinimumFractionDigits(int
the minimum number of fraction digits to be shown. newValue)Overrides java. Sets the minimum number of digits allowed in the fraction portion of a number during formatting. |
| public void | setMinimumIntegerDigits(int
the minimum number of integer digits to be shown. newValue)Overrides java. Sets the minimum number of digits allowed in the integer portion of a number during formatting. |
| public void | setParseBigDecimal(boolean
true if the parse method returns BigDecimal;
false otherwiseSets whether the |
| public void | setParseIntegerOnly(boolean
true if compact numbers should be parsed as
integers only; false otherwiseOverrides java. Sets whether or not this format parses only an integer from the number component of a compact number. |
| public void | setRoundingMode(RoundingMode
the roundingMode)RoundingMode to be usedOverrides java. Sets the |
| public void | setStrict(boolean strict)
Overrides java. Change the leniency value for parsing. |
| public String | Returns: a string identifying thisCompactNumberFormat, for debuggingOverrides java. Returns a string identifying this |
| private String | |
| private static boolean | Returns: match indicatorA string representing either a single value or a range valueOrRange, double to examine in double input)Checks if the 'input' equals the value, or within the range. |