Class CompactNumberFormat

java.lang.Object
java.text.Format
java.text.NumberFormat
java.text.CompactNumberFormat
All Implemented Interfaces:
Serializable,Cloneable

public final classCompactNumberFormatextendsNumberFormat

CompactNumberFormat is a concrete subclass ofNumberFormat 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 number7M instead of 7,000,000.00 in theUS locale. The CompactNumberFormat class is defined by LDML's specification for Compact Number Formats.

Getting a CompactNumberFormat

To get a compact number format, use one of the ways listed below.

If a standard compact format for a given locale andstyle is desired, it is recommended to use one of the NumberFormat factory methods listed above. To use an instance method defined byCompactNumberFormat, theNumberFormat returned by these factory methods should be type checked before converted toCompactNumberFormat. If the installed locale-sensitive service implementation does not support the givenLocale, the parent locale chain will be looked up, and aLocale used that is supported.

Style

When usingNumberFormat.getCompactNumberInstance(Locale, Style), a compact form can be retrieved with either aSHORT orLONG style. For example, aSHORT style compact number instance in theUS locale formats10000 as "10K". However, aLONG style instance in the same locale formats10000 as"10 thousand".

Using CompactNumberFormat

The following is an example of formatting and parsing in a localized manner,
NumberFormat compactFormat = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);compactFormat.format(1000); // returns "1K"compactFormat.parse("1K"); // returns 1000

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 number1000.0 or1000 is formatted as"1K" not"1.00K" (in theUS 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 byDecimalFormat for the specified locale is used.

Rounding

CompactNumberFormat provides rounding modes defined inRoundingMode for formatting. By default, it usesRoundingMode.HALF_EVEN.

Parsing

The default parsing behavior does not allow a grouping separator until grouping used is set totrue by usingsetGroupingUsed(boolean). The parsing of the fractional part depends on theisParseIntegerOnly(). For example, if the parse integer only is set to true, then the fractional part is skipped.

Compact Number Patterns

ThecompactPatterns inCompactNumberFormat(decimalPattern, symbols, compactPatterns) are represented as a series of strings, where each string is apattern that is used to format a range of numbers.

An example of theSHORT styled compact number patterns for theUS locale is{"", "", "", "0K", "00K", "000K", "0M", "00M", "000M", "0B", "00B", "000B", "0T", "00T", "000T"}, ranging from100 to1014. There can be any number of patterns and they are strictly index based starting from the range100. 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 range100-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.

Negative Subpatterns

A compact pattern contains a positive and negative subpattern separated by a subpattern boundary character';', 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".

Escaping Special Characters

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. These characters must be quoted using single quotes' (U+0027) unless noted otherwise, if they are to appear in the prefix or suffix as literals. For example, 0क'.'.

Plurals

CompactNumberFormat support patterns for both singular and plural compact forms. For the plural form, thePattern should consist ofPluralPattern(s) separated by a space ' ' (U+0020) that are enumerated within a pair of curly brackets '{' (U+007B) and '}' (U+007D). In this format, eachPluralPattern consists of itscount, followed by a single colon':' (U+003A) and aSimplePattern. As a space is reserved for separating subsequentPluralPatterns, it must be quoted to be used literally in either theprefix orsuffix.

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, withcount following LDML's Language Plural Rules:

Pattern:SimplePattern         '{'PluralPattern[' ' PluralPattern]optional '}'SimplePattern:PositivePatternPositivePattern[; NegativePattern]optionalPluralPattern:Count:SimplePatternCount:         "zero" / "one" / "two" / "few" / "many" / "other"PositivePattern:PrefixoptionalMinimumIntegerSuffixoptionalNegativePattern:PrefixoptionalMinimumIntegerSuffixoptionalPrefix:      Any characters except thespecial pattern charactersSuffix:      Any characters except thespecial pattern charactersMinimumInteger:      0      0MinimumInteger

Since:
12
External Specifications
See Also:
  • Constructor Details

    • CompactNumberFormat

      public CompactNumberFormat(String decimalPattern,DecimalFormatSymbols symbols,String[] compactPatterns)
      Creates aCompactNumberFormat using the given decimal pattern, decimal format symbols and compact patterns. To obtain the instance ofCompactNumberFormat with the standard compact patterns for aLocale andStyle, it is recommended to use the factory methods given byNumberFormat 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"

      Parameters:
      decimalPattern - adecimal pattern for general number formatting
      symbols - the set of symbols to be used
      compactPatterns - an array ofcompact number patterns
      Throws:
      NullPointerException - if any of the given arguments isnull
      IllegalArgumentException - if the givendecimalPattern or thecompactPatterns array contains an invalid pattern or if anull appears in the array of compact patterns
      See Also:
    • CompactNumberFormat

      public CompactNumberFormat(String decimalPattern,DecimalFormatSymbols symbols,String[] compactPatterns,String pluralRules)
      Creates aCompactNumberFormat using the given decimal pattern, decimal format symbols, compact patterns, and plural rules. To obtain the instance ofCompactNumberFormat with the standard compact patterns for aLocale,Style, andpluralRules, it is recommended to use the factory methods given byNumberFormat for compact number formatting. For example,NumberFormat.getCompactNumberInstance(Locale, Style).
      Parameters:
      decimalPattern - adecimal pattern for general number formatting
      symbols - the set of symbols to be used
      compactPatterns - an array ofcompact number patterns
      pluralRules - a String designating plural rules which associate theCount keyword, 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 isnull
      IllegalArgumentException - if the givendecimalPattern, thecompactPatterns array contains an invalid pattern, anull appears in the array of compact patterns, or if the givenpluralRules contains 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:
      format in class NumberFormat
      Parameters:
      number - the number to format
      toAppendTo - theStringBuffer to which the formatted text is to be appended
      fieldPosition - keeps track on the position of the field within the returned string. For example, for formatting a number123456789 in theUS locale, if the givenfieldPosition isNumberFormat.INTEGER_FIELD, the begin index and end index offieldPosition will 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.PREFIX andNumberFormat.Field.SUFFIX respectively.
      Returns:
      theStringBuffer passed in astoAppendTo
      Throws:
      IllegalArgumentException - ifnumber isnull or not an instance ofNumber
      NullPointerException - iftoAppendTo orfieldPosition isnull
      ArithmeticException - if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY
      See Also:
    • format

      public StringBuffer format(double number,StringBuffer result,FieldPosition fieldPosition)
      Formats a double to produce a string representing its compact form.
      Specified by:
      format in class NumberFormat
      Parameters:
      number - the double number to format
      result - where the text is to be appended
      fieldPosition - keeps track on the position of the field within the returned string. For example, to format a number1234567.89 in theUS locale if the givenfieldPosition isNumberFormat.INTEGER_FIELD, the begin index and end index offieldPosition will 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.PREFIX andNumberFormat.Field.SUFFIX respectively.
      Returns:
      theStringBuffer passed in asresult
      Throws:
      NullPointerException - ifresult orfieldPosition isnull
      ArithmeticException - if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY
      See Also:
    • format

      public StringBuffer format(long number,StringBuffer result,FieldPosition fieldPosition)
      Formats a long to produce a string representing its compact form.
      Specified by:
      format in class NumberFormat
      Parameters:
      number - the long number to format
      result - where the text is to be appended
      fieldPosition - keeps track on the position of the field within the returned string. For example, to format a number123456789 in theUS locale, if the givenfieldPosition isNumberFormat.INTEGER_FIELD, the begin index and end index offieldPosition will 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.PREFIX andNumberFormat.Field.SUFFIX respectively.
      Returns:
      theStringBuffer passed in asresult
      Throws:
      NullPointerException - ifresult orfieldPosition isnull
      ArithmeticException - if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY
      See Also:
    • formatToCharacterIterator

      public AttributedCharacterIterator formatToCharacterIterator(Object obj)
      Formats an Object producing anAttributedCharacterIterator. The returnedAttributedCharacterIterator can be used to build the resulting string, as well as to determine information about the resulting string.

      Each attribute key of theAttributedCharacterIterator will 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.PREFIX andNumberFormat.Field.SUFFIX respectively.

      Overrides:
      formatToCharacterIterator in class Format
      Parameters:
      obj - The object to format
      Returns:
      anAttributedCharacterIterator describing the formatted value
      Throws:
      NullPointerException - if obj is null
      IllegalArgumentException - when the Format cannot format the given object
      ArithmeticException - if rounding is needed with rounding mode being set toRoundingMode.UNNECESSARY
    • parse

      public Number parse(String text,ParsePosition pos)
      Parses text from the beginning of the given string to produce aNumber.

      This method attempts to parse text starting at the index given by theParsePosition. 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 theParsePosition is not changed, the error index of theParsePosition is set to the index of the character where the error occurred, andnull 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 inUS locale).

      ACompactNumberFormat 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 whenlenient, 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 whenstrict, if intext,

      • The default or a compact prefix is not found. For example, the Locale.US currency format prefix: "$"
      • The default or a compact suffix is not found. For example, aLocale.USNumberFormat.Style.SHORT compact suffix: "K"
      • isGroupingUsed() returnsfalse, and the grouping symbol is found
      • isGroupingUsed() returnstrue, andgetGroupingSize() is not adhered to
      • isParseIntegerOnly() returnstrue, and the decimal separator is found
      • isGroupingUsed() returnstrue andisParseIntegerOnly() returnsfalse, and the grouping symbol occurs after the decimal separator
      • Any other characters are found, that are not the expected symbols, and are not digits that occur within the numerical portion

      The subclass returned depends on the value ofisParseBigDecimal().

      • IfisParseBigDecimal() is false (the default), most integer values are returned asLong objects, 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 theNumber methodsdoubleValue,longValue, etc., to obtain the type they want.

      • IfisParseBigDecimal() is true, values are returned asBigDecimal objects. The special cases negative and positive infinity and NaN are returned asDouble instances holding the values of the correspondingDouble constants.

      CompactNumberFormat parses all Unicode characters that represent decimal digits, as defined byCharacter.digit(). In addition,CompactNumberFormat also recognizes as digits the ten consecutive characters starting with the localized zero digit defined in theDecimalFormatSymbols object.

      CompactNumberFormat parse does not allow parsing scientific notations. For example, parsing a string"1.05E4K" inUS locale breaks at character 'E' and returns 1.05.

      Specified by:
      parse in class NumberFormat
      Parameters:
      text - the string to be parsed
      pos - aParsePosition object with index and error index information as described above
      Returns:
      the parsed value, ornull if the parse fails
      Throws:
      NullPointerException - iftext orpos is null
      See Also:
    • 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:
      setMaximumIntegerDigits in class NumberFormat
      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:
      setMinimumIntegerDigits in class NumberFormat
      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:
      setMinimumFractionDigits in class NumberFormat
      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:
      setMaximumFractionDigits in class NumberFormat
      Parameters:
      newValue - the maximum number of fraction digits to be shown
      See Also:
    • getRoundingMode

      public RoundingMode getRoundingMode()
      Gets theRoundingMode used in thisCompactNumberFormat.
      Overrides:
      getRoundingMode in class NumberFormat
      Returns:
      theRoundingMode used for thisCompactNumberFormat
      See Also:
    • setRoundingMode

      public void setRoundingMode(RoundingMode roundingMode)
      Sets theRoundingMode used in thisCompactNumberFormat.
      Overrides:
      setRoundingMode in class NumberFormat
      Parameters:
      roundingMode - theRoundingMode to be used
      Throws:
      NullPointerException - ifroundingMode isnull
      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 - ifnewValue is 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 number12346567890987654 can be formatted as"12,347 trillion" in theUS locale. The grouping separator is locale dependent.
      Overrides:
      isGroupingUsed in class NumberFormat
      Returns:
      true if grouping is used;false otherwise
      See Also:
    • setGroupingUsed

      public void setGroupingUsed(boolean newValue)
      Sets whether or not grouping will be used in this format.
      Overrides:
      setGroupingUsed in class NumberFormat
      Parameters:
      newValue -true if grouping is used;false otherwise
      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:
      isParseIntegerOnly in class NumberFormat
      Implementation Requirements:
      This implementation does not set theParsePosition index to the position of the decimal symbol, but rather the end of the string.
      Returns:
      true if compact numbers should be parsed as integers only;false otherwise
    • 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:
      setParseIntegerOnly in class NumberFormat
      Parameters:
      value -true if compact numbers should be parsed as integers only;false otherwise
      See Also:
    • isStrict

      public boolean isStrict()
      Returnstrue if this format will parse numbers strictly;false otherwise.
      Overrides:
      isStrict in class NumberFormat
      Returns:
      true if this format will parse numbers strictly;false otherwise
      Since:
      23
      See Also:
    • setStrict

      public void setStrict(boolean strict)
      Change the leniency value for parsing. Parsing can either be strict or lenient, by default it is lenient.
      Overrides:
      setStrict in class NumberFormat
      Parameters:
      strict -true if parsing should be done strictly;false otherwise
      Since:
      23
      See Also:
    • isParseBigDecimal

      public boolean isParseBigDecimal()
      Returns whether theparse(String, ParsePosition) method returnsBigDecimal. The default value is false.
      Returns:
      true if the parse method returns BigDecimal;false otherwise
      See Also:
    • setParseBigDecimal

      public void setParseBigDecimal(boolean newValue)
      Sets whether theparse(String, ParsePosition) method returnsBigDecimal.
      Parameters:
      newValue -true if the parse method returns BigDecimal;false otherwise
      See Also:
    • equals

      public boolean equals(Object obj)
      Compares the specified object with thisCompactNumberFormat for equality. Returns true if the object is also aCompactNumberFormat and the two formats would format any value the same.
      Overrides:
      equals in class NumberFormat
      Implementation Requirements:
      This method performs an equality check with a notion of class identity based ongetClass(), rather thaninstanceof. Therefore, in the equals methods in subclasses, no instance of this class should compare as equal to an instance of a subclass.
      Parameters:
      obj - the object to compare with
      Returns:
      true if this is equal to the otherCompactNumberFormat
      See Also:
    • hashCode

      public int hashCode()
      Returns the hash code for thisCompactNumberFormat.
      Overrides:
      hashCode in class NumberFormat
      Implementation Requirements:
      Non-transient instance fields of this class are used to calculate a hash code value which adheres to the contract defined inObjects.hashCode(java.lang.Object)
      Returns:
      the hash code for thisCompactNumberFormat
      See Also:
    • toString

      public String toString()
      Returns a string identifying thisCompactNumberFormat, for debugging.
      Overrides:
      toString in class Object
      Returns:
      a string identifying thisCompactNumberFormat, for debugging
    • clone

      public CompactNumberFormat clone()
      Creates and returns a copy of thisCompactNumberFormat instance.
      Overrides:
      clone in class NumberFormat
      Returns:
      a clone of this instance
      See Also: