- All Implemented Interfaces:
Serializable,Cloneable
CompactNumberFormat is a concrete subclass of NumberFormat
that formats a decimal number in its compact form.
The compact number formatting is designed for the environment where the space
is limited, and the formatted string can be displayed in that limited space.
It is defined by LDML's specification for
Compact Number Formats. A compact number formatting refers
to the representation of a number in a shorter form, based on the patterns
provided for a given locale.
For example:
In the US locale, 1000 can be formatted
as "1K", and 1000000 as "1M", depending upon the
style used.
In the "hi_IN" locale, 1000 can be formatted as
"1 हज़ार", and 50000000 as "5 क.",
depending upon the style used.
To obtain a CompactNumberFormat for a locale, use one
of the factory methods given by NumberFormat for compact number
formatting. For example,
NumberFormat.getCompactNumberInstance(Locale, Style).
NumberFormat fmt = NumberFormat.getCompactNumberInstance( Locale.forLanguageTag("hi-IN"), NumberFormat.Style.SHORT); String result = fmt.format(1000);
Style
A number can be formatted in the compact forms with two different
styles, SHORT
and LONG. Use
NumberFormat.getCompactNumberInstance(Locale, Style) for formatting and
parsing a number in SHORT or
LONG compact form,
where the given Style parameter requests the desired
format. A SHORT style
compact number instance in the US locale formats
10000 as "10K". However, a
LONG style instance in same locale
formats 10000 as "10 thousand".
Compact Number Patterns
The compact number patterns are represented in a series of patterns where each
pattern is used to format a range of numbers. An example of
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, pattern at index 3
("0K") is used for formatting number >= 1000 and number < 10000,
pattern at index 4 ("00K") is used for formatting
number >= 10000 and number < 100000 and so on. In most of the 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.
A compact pattern contains a positive and negative subpattern
separated by a subpattern boundary character ';' (U+003B),
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".
Many characters in a compact pattern are taken literally, they are matched
during parsing and output unchanged during formatting.
Special characters,
on the other hand, stand for other characters, strings, or classes of
characters. They must be quoted, using single quote ' (U+0027)
unless noted otherwise, if they are to appear in the prefix or suffix
as literals. For example, 0क'.'.
Plurals
In case some localization requires compact number patterns to be different for
plurals, each singular and plural pattern can be enumerated within a pair of
curly brackets '{' (U+007B) and '}' (U+007D), separated
by a space ' ' (U+0020). If this format is used, each pattern needs to be
prepended by its count, followed by a single colon ':' (U+003A).
If the pattern includes spaces literally, they must be quoted.
For example, the compact number pattern representing millions in German locale can be
specified as "{one:0' 'Million other:0' 'Millionen}". The count
follows LDML's
Language Plural Rules.
A compact pattern has the following syntax:
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 Unicode characters except U+FFFE, U+FFFF, and
special characters.
Suffix:
Any Unicode characters except U+FFFE, U+FFFF, and
special characters.
MinimumInteger:
0
0 MinimumInteger
Formatting
The default formatting behavior returns a formatted string with no fractional digits, however users can use thesetMinimumFractionDigits(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.
Parsing
The default parsing behavior does not allow a grouping separator until grouping used is set totrue 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.
Rounding
CompactNumberFormat provides rounding modes defined in
RoundingMode for formatting. By default, it uses
RoundingMode.HALF_EVEN.- Since:
- 12
- External Specifications
- See Also:
-
Nested Class Summary
Nested classes/interfaces declared in class java.text.NumberFormat
NumberFormat.Field, NumberFormat.Style -
Field Summary
Fields declared in class java.text.NumberFormat
FRACTION_FIELD, INTEGER_FIELD -
Constructor Summary
ConstructorsConstructorDescriptionCompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns) Creates aCompactNumberFormatusing the given decimal pattern, decimal format symbols and compact patterns.CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns, String pluralRules) Creates aCompactNumberFormatusing the given decimal pattern, decimal format symbols, compact patterns, and plural rules. -
Method Summary
Modifier and TypeMethodDescriptionclone()Creates and returns a copy of thisCompactNumberFormatinstance.booleanChecks if thisCompactNumberFormatis equal to the specifiedobj.format(double number, StringBuffer result, FieldPosition fieldPosition) Formats a double to produce a string representing its compact form.format(long number, StringBuffer result, FieldPosition fieldPosition) Formats a long to produce a string representing its compact form.final StringBufferformat(Object number, StringBuffer toAppendTo, FieldPosition fieldPosition) Formats a number to produce a string representing its compact form.Formats an Object producing anAttributedCharacterIterator.intReturns the grouping size.Gets theRoundingModeused in thisCompactNumberFormat.inthashCode()Returns the hash code for thisCompactNumberFormatinstance.booleanReturns true if grouping is used in this format.booleanReturns whether theparse(String, ParsePosition)method returnsBigDecimal.booleanReturns true if this format parses only an integer from the number component of a compact number.parse(String text, ParsePosition pos) Parses a compact number from a string to produce aNumber.voidsetGroupingSize(int newValue) Sets the grouping size.voidsetGroupingUsed(boolean newValue) Sets whether or not grouping will be used in this format.voidsetMaximumFractionDigits(int newValue) Sets the maximum number of digits allowed in the fraction portion of a number.voidsetMaximumIntegerDigits(int newValue) Sets the maximum number of digits allowed in the integer portion of a number.voidsetMinimumFractionDigits(int newValue) Sets the minimum number of digits allowed in the fraction portion of a number.voidsetMinimumIntegerDigits(int newValue) Sets the minimum number of digits allowed in the integer portion of a number.voidsetParseBigDecimal(boolean newValue) Sets whether theparse(String, ParsePosition)method returnsBigDecimal.voidsetParseIntegerOnly(boolean value) Sets whether or not this format parses only an integer from the number component of a compact number.voidsetRoundingMode(RoundingMode roundingMode) Sets theRoundingModeused in thisCompactNumberFormat.Methods declared in class java.text.NumberFormat
format, format, getAvailableLocales, getCompactNumberInstance, getCompactNumberInstance, getCurrency, getCurrencyInstance, getCurrencyInstance, getInstance, getInstance, getIntegerInstance, getIntegerInstance, getMaximumFractionDigits, getMaximumIntegerDigits, getMinimumFractionDigits, getMinimumIntegerDigits, getNumberInstance, getNumberInstance, getPercentInstance, getPercentInstance, parse, parseObject, setCurrencyMethods declared in class java.text.Format
format, parseObject
-
Constructor Details
-
CompactNumberFormat
public CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns) Creates aCompactNumberFormatusing the given decimal pattern, decimal format symbols and compact patterns. To obtain the instance ofCompactNumberFormatwith the standard compact patterns for aLocaleandStyle, it is recommended to use the factory methods given byNumberFormatfor compact number formatting. For example,NumberFormat.getCompactNumberInstance(Locale, Style).- Parameters:
decimalPattern- a decimal pattern for general number formattingsymbols- the set of symbols to be usedcompactPatterns- an array of compact number patterns- Throws:
NullPointerException- if any of the given arguments isnullIllegalArgumentException- if the givendecimalPatternor thecompactPatternsarray contains an invalid pattern or if anullappears in the array of compact patterns- See Also:
-
CompactNumberFormat
public CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns, String pluralRules) Creates aCompactNumberFormatusing the given decimal pattern, decimal format symbols, compact patterns, and plural rules. To obtain the instance ofCompactNumberFormatwith the standard compact patterns for aLocale,Style, andpluralRules, it is recommended to use the factory methods given byNumberFormatfor compact number formatting. For example,NumberFormat.getCompactNumberInstance(Locale, Style).- Parameters:
decimalPattern- a decimal pattern for general number formattingsymbols- the set of symbols to be usedcompactPatterns- an array of compact number patternspluralRules- a String designating plural rules which associate theCountkeyword, such as "one", and the actual integer number. Its syntax is defined in Unicode Consortium's Plural rules syntax- Throws:
NullPointerException- if any of the given arguments isnullIllegalArgumentException- if the givendecimalPattern, thecompactPatternsarray contains an invalid pattern, anullappears in the array of compact patterns, or if the givenpluralRulescontains an invalid syntax- Since:
- 14
- External Specifications
- See Also:
-
-
Method Details
-
format
public final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition fieldPosition) Formats a number to produce a string representing its compact form. The number can be of any subclass ofNumber.- Overrides:
formatin classNumberFormat- Parameters:
number- the number to formattoAppendTo- theStringBufferto which the formatted text is to be appendedfieldPosition- keeps track on the position of the field within the returned string. For example, for formatting a number123456789in theUS locale, if the givenfieldPositionisNumberFormat.INTEGER_FIELD, the begin index and end index offieldPositionwill be set to 0 and 3, respectively for the output string123M. Similarly, positions of the prefix and the suffix fields can be obtained usingNumberFormat.Field.PREFIXandNumberFormat.Field.SUFFIXrespectively.- Returns:
- the
StringBufferpassed in astoAppendTo - Throws:
IllegalArgumentException- ifnumberisnullor not an instance ofNumberNullPointerException- iftoAppendToorfieldPositionisnullArithmeticException- if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY- See Also:
-
format
Formats a double to produce a string representing its compact form.- Specified by:
formatin classNumberFormat- Parameters:
number- the double number to formatresult- where the text is to be appendedfieldPosition- keeps track on the position of the field within the returned string. For example, to format a number1234567.89in theUS localeif the givenfieldPositionisNumberFormat.INTEGER_FIELD, the begin index and end index offieldPositionwill be set to 0 and 1, respectively for the output string1M. Similarly, positions of the prefix and the suffix fields can be obtained usingNumberFormat.Field.PREFIXandNumberFormat.Field.SUFFIXrespectively.- Returns:
- the
StringBufferpassed in asresult - Throws:
NullPointerException- ifresultorfieldPositionisnullArithmeticException- if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY- See Also:
-
format
Formats a long to produce a string representing its compact form.- Specified by:
formatin classNumberFormat- Parameters:
number- the long number to formatresult- where the text is to be appendedfieldPosition- keeps track on the position of the field within the returned string. For example, to format a number123456789in theUS locale, if the givenfieldPositionisNumberFormat.INTEGER_FIELD, the begin index and end index offieldPositionwill be set to 0 and 3, respectively for the output string123M. Similarly, positions of the prefix and the suffix fields can be obtained usingNumberFormat.Field.PREFIXandNumberFormat.Field.SUFFIXrespectively.- Returns:
- the
StringBufferpassed in asresult - Throws:
NullPointerException- ifresultorfieldPositionisnullArithmeticException- if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY- See Also:
-
formatToCharacterIterator
Formats an Object producing anAttributedCharacterIterator. The returnedAttributedCharacterIteratorcan be used to build the resulting string, as well as to determine information about the resulting string.Each attribute key of the
AttributedCharacterIteratorwill be of typeNumberFormat.Field, with the attribute value being the same as the attribute key. The prefix and the suffix parts of the returned iterator (if present) are represented by the attributesNumberFormat.Field.PREFIXandNumberFormat.Field.SUFFIXrespectively.- Overrides:
formatToCharacterIteratorin classFormat- Parameters:
obj- The object to format- Returns:
- an
AttributedCharacterIteratordescribing the formatted value - Throws:
NullPointerException- if obj is nullIllegalArgumentException- when the Format cannot format the given objectArithmeticException- if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY
-
parse
Parses a compact number from a string to produce aNumber.The method attempts to parse text starting at the index given by
pos. If parsing succeeds, then the index ofposis updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed number is returned. The updatedposcan be used to indicate the starting point for the next call to this method. If an error occurs, then the index ofposis not changed, the error index ofposis set to the index of the character where the error occurred, andnullis returned.The value is the numeric part in the given text multiplied by the numeric equivalent of the affix attached (For example, "K" = 1000 in
US locale). The subclass returned depends on the value ofisParseBigDecimal().- If
isParseBigDecimal()is false (the default), most integer values are returned asLongobjects, no matter how they are written:"17K"and"17.000K"both parse toLong.valueOf(17000). If the value cannot fit intoLong, then the result is returned asDouble. This includes values with a fractional part, infinite values,NaN, and the value -0.0.Callers may use the
NumbermethodsdoubleValue,longValue, etc., to obtain the type they want. - If
isParseBigDecimal()is true, values are returned asBigDecimalobjects. The special cases negative and positive infinity and NaN are returned asDoubleinstances holding the values of the correspondingDoubleconstants.
CompactNumberFormatparses all Unicode characters that represent decimal digits, as defined byCharacter.digit(). In addition,CompactNumberFormatalso recognizes as digits the ten consecutive characters starting with the localized zero digit defined in theDecimalFormatSymbolsobject.CompactNumberFormatparse does not allow parsing scientific notations. For example, parsing a string"1.05E4K"inUS localebreaks at character 'E' and returns 1.05.- Specified by:
parsein classNumberFormat- Parameters:
text- the string to be parsedpos- aParsePositionobject with index and error index information as described above- Returns:
- the parsed value, or
nullif the parse fails - Throws:
NullPointerException- iftextorposis null- See Also:
- If
-
setMaximumIntegerDigits
public void setMaximumIntegerDigits(int newValue) Sets the maximum number of digits allowed in the integer portion of a number. The maximum allowed integer range is 309, if thenewValue> 309, then the maximum integer digits count is set to 309. Negative input values are replaced with 0.- Overrides:
setMaximumIntegerDigitsin classNumberFormat- Parameters:
newValue- the maximum number of integer digits to be shown- See Also:
-
setMinimumIntegerDigits
public void setMinimumIntegerDigits(int newValue) Sets the minimum number of digits allowed in the integer portion of a number. The maximum allowed integer range is 309, if thenewValue> 309, then the minimum integer digits count is set to 309. Negative input values are replaced with 0.- Overrides:
setMinimumIntegerDigitsin classNumberFormat- Parameters:
newValue- the minimum number of integer digits to be shown- See Also:
-
setMinimumFractionDigits
public void setMinimumFractionDigits(int newValue) Sets the minimum number of digits allowed in the fraction portion of a number. The maximum allowed fraction range is 340, if thenewValue> 340, then the minimum fraction digits count is set to 340. Negative input values are replaced with 0.- Overrides:
setMinimumFractionDigitsin classNumberFormat- Parameters:
newValue- the minimum number of fraction digits to be shown- See Also:
-
setMaximumFractionDigits
public void setMaximumFractionDigits(int newValue) Sets the maximum number of digits allowed in the fraction portion of a number. The maximum allowed fraction range is 340, if thenewValue> 340, then the maximum fraction digits count is set to 340. Negative input values are replaced with 0.- Overrides:
setMaximumFractionDigitsin classNumberFormat- Parameters:
newValue- the maximum number of fraction digits to be shown- See Also:
-
getRoundingMode
Gets theRoundingModeused in thisCompactNumberFormat.- Overrides:
getRoundingModein classNumberFormat- Returns:
- the
RoundingModeused for thisCompactNumberFormat - See Also:
-
setRoundingMode
Sets theRoundingModeused in thisCompactNumberFormat.- Overrides:
setRoundingModein classNumberFormat- Parameters:
roundingMode- theRoundingModeto be used- Throws:
NullPointerException- ifroundingModeisnull- See Also:
-
getGroupingSize
public int getGroupingSize()Returns the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the compact number"12,347 trillion"for theUS locale, the grouping size is 3.- Returns:
- the grouping size
- See Also:
-
setGroupingSize
public void setGroupingSize(int newValue) Sets the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the compact number"12,347 trillion"for theUS locale, the grouping size is 3. The grouping size must be greater than or equal to zero and less than or equal to 127.- Parameters:
newValue- the new grouping size- Throws:
IllegalArgumentException- ifnewValueis negative or larger than 127- See Also:
-
isGroupingUsed
public boolean isGroupingUsed()Returns true if grouping is used in this format. For example, with grouping on and grouping size set to 3, the number12346567890987654can be formatted as"12,347 trillion"in theUS locale. The grouping separator is locale dependent.- Overrides:
isGroupingUsedin classNumberFormat- Returns:
trueif grouping is used;falseotherwise- See Also:
-
setGroupingUsed
public void setGroupingUsed(boolean newValue) Sets whether or not grouping will be used in this format.- Overrides:
setGroupingUsedin classNumberFormat- Parameters:
newValue-trueif grouping is used;falseotherwise- See Also:
-
isParseIntegerOnly
public boolean isParseIntegerOnly()Returns true if this format parses only an integer from the number component of a compact number. Parsing an integer means that only an integer is considered from the number component, prefix/suffix is still considered to compute the resulting output. For example, in theUS locale, if this method returnstrue, the string"1234.78 thousand"would be parsed as the value1234000(1234 (integer part) * 1000 (thousand)) and the fractional part would be skipped. The exact format accepted by the parse operation is locale dependent.- Overrides:
isParseIntegerOnlyin classNumberFormat- Returns:
trueif compact numbers should be parsed as integers only;falseotherwise
-
setParseIntegerOnly
public void setParseIntegerOnly(boolean value) Sets whether or not this format parses only an integer from the number component of a compact number.- Overrides:
setParseIntegerOnlyin classNumberFormat- Parameters:
value-trueif compact numbers should be parsed as integers only;falseotherwise- See Also:
-
isParseBigDecimal
public boolean isParseBigDecimal()Returns whether theparse(String, ParsePosition)method returnsBigDecimal. The default value is false.- Returns:
trueif the parse method returns BigDecimal;falseotherwise- See Also:
-
setParseBigDecimal
public void setParseBigDecimal(boolean newValue) Sets whether theparse(String, ParsePosition)method returnsBigDecimal.- Parameters:
newValue-trueif the parse method returns BigDecimal;falseotherwise- See Also:
-
equals
Checks if thisCompactNumberFormatis equal to the specifiedobj. The objects of typeCompactNumberFormatare compared, other types return false; obeys the general contract ofObject.equals.- Overrides:
equalsin classNumberFormat- Parameters:
obj- the object to compare with- Returns:
- true if this is equal to the other
CompactNumberFormat - See Also:
-
hashCode
public int hashCode()Returns the hash code for thisCompactNumberFormatinstance.- Overrides:
hashCodein classNumberFormat- Returns:
- hash code for this
CompactNumberFormat - See Also:
-
clone
Creates and returns a copy of thisCompactNumberFormatinstance.- Overrides:
clonein classNumberFormat- Returns:
- a clone of this instance
- See Also:
-