Serializable, Cloneablepublic final class CompactNumberFormat extends NumberFormat
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 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". ' (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.Field, NumberFormat.Style
FRACTION_FIELD, INTEGER_FIELD
| Constructor | Description |
|---|---|
CompactNumberFormat |
Creates a CompactNumberFormat using the given decimal pattern, decimal format symbols and compact patterns. |
CompactNumberFormat |
Creates a CompactNumberFormat using the given decimal pattern, decimal format symbols, compact patterns, and plural rules. |
| Modifier and Type | Method | Description |
|---|---|---|
CompactNumberFormat |
clone() |
Creates and returns a copy of this CompactNumberFormat instance. |
boolean |
equals |
Compares the specified object with this CompactNumberFormat for equality. |
StringBuffer |
format |
Formats a double to produce a string representing its compact form. |
StringBuffer |
format |
Formats a long to produce a string representing its compact form. |
final StringBuffer |
format |
Formats a number to produce a string representing its compact form. |
AttributedCharacterIterator |
formatToCharacterIterator |
Formats an Object producing an AttributedCharacterIterator. |
int |
getGroupingSize() |
Returns the grouping size. |
RoundingMode |
getRoundingMode() |
Gets the RoundingMode used in this CompactNumberFormat. |
int |
hashCode() |
Returns the hash code for this CompactNumberFormat. |
boolean |
isGroupingUsed() |
Returns true if grouping is used in this format. |
boolean |
isParseBigDecimal() |
Returns whether the parse(String, ParsePosition) method returns BigDecimal. |
boolean |
isParseIntegerOnly() |
Returns true if this format parses only an integer from the number component of a compact number. |
boolean |
isStrict() |
Returns true if this format will parse numbers strictly; false otherwise. |
Number |
parse |
Parses text from the beginning of the given string to produce a Number. |
void |
setGroupingSize |
Sets the grouping size. |
void |
setGroupingUsed |
Sets whether or not grouping will be used in this format. |
void |
setMaximumFractionDigits |
Sets the maximum number of digits allowed in the fraction portion of a number during formatting. |
void |
setMaximumIntegerDigits |
Sets the maximum number of digits allowed in the integer portion of a number during formatting. |
void |
setMinimumFractionDigits |
Sets the minimum number of digits allowed in the fraction portion of a number during formatting. |
void |
setMinimumIntegerDigits |
Sets the minimum number of digits allowed in the integer portion of a number during formatting. |
void |
setParseBigDecimal |
Sets whether the parse(String, ParsePosition) method returns BigDecimal. |
void |
setParseIntegerOnly |
Sets whether or not this format parses only an integer from the number component of a compact number. |
void |
setRoundingMode |
Sets the RoundingMode used in this CompactNumberFormat. |
void |
setStrict |
Change the leniency value for parsing. |
String |
toString() |
Returns a string identifying this CompactNumberFormat, for debugging. |
format, format, getAvailableLocales, getCompactNumberInstance, getCompactNumberInstance, getCurrency, getCurrencyInstance, getCurrencyInstance, getInstance, getInstance, getIntegerInstance, getIntegerInstance, getMaximumFractionDigits, getMaximumIntegerDigits, getMinimumFractionDigits, getMinimumIntegerDigits, getNumberInstance, getNumberInstance, getPercentInstance, getPercentInstance, parse, parseObject, setCurrency
format, parseObject
public CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns)
CompactNumberFormat using the given decimal pattern, decimal format symbols and compact patterns. To obtain the instance of CompactNumberFormat with the standard compact patterns for a Locale and Style, it is recommended to use the factory methods given by NumberFormat for compact number formatting. Below is an example of using the constructor,
String[] compactPatterns = {"", "", "", "a lot"};
NumberFormat fmt = new CompactNumberFormat("00", DecimalFormatSymbols.getInstance(Locale.US), compactPatterns);
fmt.format(1); // returns "01"
fmt.format(1000); // returns "a lot"
decimalPattern - a decimal pattern for general number formattingsymbols - the set of symbols to be usedcompactPatterns - an array of compact number patterns
NullPointerException - if any of the given arguments is null
IllegalArgumentException - if the given decimalPattern or the compactPatterns array contains an invalid pattern or if a null appears in the array of compact patternspublic CompactNumberFormat(String decimalPattern, DecimalFormatSymbols symbols, String[] compactPatterns, String pluralRules)
CompactNumberFormat using the given decimal pattern, decimal format symbols, compact patterns, and plural rules. To obtain the instance of CompactNumberFormat with the standard compact patterns for a Locale, Style, and pluralRules, it is recommended to use the factory methods given by NumberFormat for compact number formatting. For example, NumberFormat.getCompactNumberInstance(Locale, Style).decimalPattern - a decimal pattern for general number formattingsymbols - the set of symbols to be usedcompactPatterns - an array of compact number patterns
pluralRules - a String designating plural rules which associate the Count keyword, such as "one", and the actual integer number. Its syntax is defined in Unicode Consortium's Plural rules syntax
NullPointerException - if any of the given arguments is null
IllegalArgumentException - if the given decimalPattern, the compactPatterns array contains an invalid pattern, a null appears in the array of compact patterns, or if the given pluralRules contains an invalid syntaxpublic final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition fieldPosition)
Number.format in class NumberFormat
number - the number to formattoAppendTo - the StringBuffer to 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 number 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.Field.PREFIX and NumberFormat.Field.SUFFIX respectively.StringBuffer passed in as toAppendTo
IllegalArgumentException - if number is null or not an instance of Number
NullPointerException - if toAppendTo or fieldPosition is null
ArithmeticException - if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY
public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition)
format in class NumberFormat
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 number 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.Field.PREFIX and NumberFormat.Field.SUFFIX respectively.StringBuffer passed in as result
NullPointerException - if result or fieldPosition is null
ArithmeticException - if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY
public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition)
format in class NumberFormat
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 number 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.Field.PREFIX and NumberFormat.Field.SUFFIX respectively.StringBuffer passed in as result
NullPointerException - if result or fieldPosition is null
ArithmeticException - if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY
public AttributedCharacterIterator formatToCharacterIterator(Object obj)
AttributedCharacterIterator. The returned AttributedCharacterIterator can be used to build the resulting string, as well as to determine information about the resulting string. Each attribute key of the AttributedCharacterIterator will be of type NumberFormat.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 attributes NumberFormat.Field.PREFIX and NumberFormat.Field.SUFFIX respectively.
formatToCharacterIterator in class Format
obj - The object to formatAttributedCharacterIterator describing the formatted valueNullPointerException - if obj is nullIllegalArgumentException - when the Format cannot format the given objectArithmeticException - if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY
public Number parse(String text, ParsePosition pos)
Number. This method attempts to parse text starting at the index given by the ParsePosition. If parsing succeeds, then the index of the
ParsePosition is 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 updated
ParsePosition can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of the ParsePosition is not changed, the error index of the ParsePosition is set to the index of the character where the error occurred, and null is returned.
This method will return a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double.
The returned 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).
A CompactNumberFormat can match the default prefix/suffix to a compact prefix/suffix interchangeably.
Parsing can be done in either a strict or lenient manner, by default it is lenient.
Parsing fails when lenient, if the prefix and/or suffix are non-empty and cannot be found due to parsing ending early, or the first character after the prefix cannot be parsed.
Parsing fails when strict, if in text,
Locale.US currency format prefix: "$" Locale.US NumberFormat.Style.SHORT compact suffix: "K" isGroupingUsed() returns false, and the grouping symbol is found isGroupingUsed() returns true, and getGroupingSize() is not adhered to isParseIntegerOnly() returns true, and the decimal separator is found isGroupingUsed() returns true and isParseIntegerOnly() returns false, and the grouping symbol occurs after the decimal separator The subclass returned depends on the value of isParseBigDecimal().
isParseBigDecimal() is false (the default), most integer values are returned as Long objects, no matter how they are written: "17K" and "17.000K" both parse to Long.valueOf(17000). If the value cannot fit into Long, then the result is returned as Double. This includes values with a fractional part, infinite values, NaN, and the value -0.0. Callers may use the Number methods doubleValue, longValue, etc., to obtain the type they want.
isParseBigDecimal() is true, values are returned as BigDecimal objects. The special cases negative and positive infinity and NaN are returned as Double instances holding the values of the corresponding Double constants. CompactNumberFormat parses all Unicode characters that represent decimal digits, as defined by Character.digit(). In addition, CompactNumberFormat also recognizes as digits the ten consecutive characters starting with the localized zero digit defined in the DecimalFormatSymbols object.
CompactNumberFormat parse does not allow parsing scientific notations. For example, parsing a string "1.05E4K" in US locale breaks at character 'E' and returns 1.05.
parse in class NumberFormat
text - the string to be parsedpos - a ParsePosition object with index and error index information as described abovenull if the parse failsNullPointerException - if text or pos is nullpublic void setMaximumIntegerDigits(int newValue)
maximumIntegerDigits must be ≥ minimumIntegerDigits. If the new value for
maximumIntegerDigits is less than the current value of minimumIntegerDigits, then minimumIntegerDigits will also be set to the new value. Negative input values are replaced with 0. The maximum allowed integer range is 309, if the newValue > 309, then the maximum integer digits count is set to 309.
setMaximumIntegerDigits in class NumberFormat
newValue - the maximum number of integer digits to be shown.public void setMinimumIntegerDigits(int newValue)
minimumIntegerDigits must be ≤ maximumIntegerDigits. If the new value for minimumIntegerDigits exceeds the current value of maximumIntegerDigits, then
maximumIntegerDigits will also be set to the new value. Negative input values are replaced with 0. The maximum allowed integer range is 309, if the newValue > 309, then the minimum integer digits count is set to 309.
setMinimumIntegerDigits in class NumberFormat
newValue - the minimum number of integer digits to be shown.public void setMinimumFractionDigits(int newValue)
minimumFractionDigits must be ≤ maximumFractionDigits. If the new value for
minimumFractionDigits exceeds the current value of
maximumFractionDigits, then maximumFractionDigits will also be set to the new value. Negative input values are replaced with 0. The maximum allowed fraction range is 340, if the newValue > 340, then the minimum fraction digits count is set to 340.
setMinimumFractionDigits in class NumberFormat
newValue - the minimum number of fraction digits to be shown.public void setMaximumFractionDigits(int newValue)
maximumFractionDigits must be ≥ minimumFractionDigits. If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits will also be set to the new value. Negative input values are replaced with 0. The maximum allowed fraction range is 340, if the newValue > 340, then the maximum fraction digits count is set to 340.
setMaximumFractionDigits in class NumberFormat
newValue - the maximum number of fraction digits to be shown.public RoundingMode getRoundingMode()
RoundingMode used in this CompactNumberFormat.getRoundingMode in class NumberFormat
RoundingMode used for this CompactNumberFormat
public void setRoundingMode(RoundingMode roundingMode)
RoundingMode used in this CompactNumberFormat.setRoundingMode in class NumberFormat
roundingMode - the RoundingMode to be usedNullPointerException - if roundingMode is null
public int getGroupingSize()
"12,347 trillion" for the US locale, the grouping size is 3.public void setGroupingSize(int newValue)
"12,347 trillion" for the US locale, the grouping size is 3. The grouping size must be greater than or equal to zero and less than or equal to 127.newValue - the new grouping sizeIllegalArgumentException - if newValue is negative or larger than 127public boolean isGroupingUsed()
12346567890987654 can be formatted as "12,347 trillion" in the US locale. The grouping separator is locale dependent.isGroupingUsed in class NumberFormat
true if grouping is used; false otherwisepublic void setGroupingUsed(boolean newValue)
setGroupingUsed in class NumberFormat
newValue - true if grouping is used; false otherwisepublic boolean isParseIntegerOnly()
US locale, if this method returns true, the string "1234.78 thousand" would be parsed as the value 1234000 (1234 (integer part) * 1000 (thousand)) and the fractional part would be skipped. The exact format accepted by the parse operation is locale dependent.isParseIntegerOnly in class NumberFormat
ParsePosition index to the position of the decimal symbol, but rather the end of the string.true if compact numbers should be parsed as integers only; false otherwisepublic void setParseIntegerOnly(boolean value)
setParseIntegerOnly in class NumberFormat
value - true if compact numbers should be parsed as integers only; false otherwisepublic boolean isStrict()
true if this format will parse numbers strictly; false otherwise.isStrict in class NumberFormat
true if this format will parse numbers strictly; false otherwisepublic void setStrict(boolean strict)
setStrict in class NumberFormat
strict - true if parsing should be done strictly; false otherwisepublic boolean isParseBigDecimal()
parse(String, ParsePosition) method returns BigDecimal. The default value is false.true if the parse method returns BigDecimal; false otherwisepublic void setParseBigDecimal(boolean newValue)
parse(String, ParsePosition) method returns BigDecimal.newValue - true if the parse method returns BigDecimal; false otherwisepublic boolean equals(Object obj)
CompactNumberFormat for equality. Returns true if the object is also a CompactNumberFormat and the two formats would format any value the same.equals in class NumberFormat
getClass(), rather than instanceof. Therefore, in the equals methods in subclasses, no instance of this class should compare as equal to an instance of a subclass.obj - the object to compare withCompactNumberFormat
public int hashCode()
CompactNumberFormat.hashCode in class NumberFormat
Objects.hashCode(Object)
CompactNumberFormat
public CompactNumberFormat clone()
CompactNumberFormat instance.clone in class NumberFormat
© 1993, 2025, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/text/CompactNumberFormat.html