Most visited

Recently visited

Added in API level 24

PluralFormat

public class PluralFormat
extends UFormat

java.lang.Object
   ↳ java.text.Format
     ↳ android.icu.text.UFormat
       ↳ android.icu.text.PluralFormat


PluralFormat supports the creation of internationalized messages with plural inflection. It is based on plural selection, i.e. the caller specifies messages for each plural case that can appear in the user's language and the PluralFormat selects the appropriate message based on the number.

The Problem of Plural Forms in Internationalized Messages

Different languages have different ways to inflect plurals. Creating internationalized messages that include plural forms is only feasible when the framework is able to handle plural forms of all languages correctly. ChoiceFormat doesn't handle this well, because it attaches a number interval to each message and selects the message whose interval contains a given number. This can only handle a finite number of intervals. But in some languages, like Polish, one plural case applies to infinitely many intervals (e.g., the paucal case applies to numbers ending with 2, 3, or 4 except those ending with 12, 13, or 14). Thus ChoiceFormat is not adequate.

PluralFormat deals with this by breaking the problem into two parts:

Usage of PluralFormat

Note: Typically, plural formatting is done via MessageFormat with a plural argument type, rather than using a stand-alone PluralFormat.

This discussion assumes that you use PluralFormat with a predefined set of plural rules. You can create one using one of the constructors that takes a ULocale object. To specify the message pattern, you can either pass it to the constructor or set it explicitly using the applyPattern() method. The format() method takes a number object and selects the message of the matching plural case. This message will be returned.

Patterns and Their Interpretation

The pattern text defines the message output for each plural case of the specified locale. Syntax:

 pluralStyle = [offsetValue] (selector '{' message '}')+
 offsetValue = "offset:" number
 selector = explicitValue | keyword
 explicitValue = '=' number  // adjacent, no white space in between
 keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
 message: see MessageFormat
 
Pattern_White_Space between syntax elements is ignored, except between the {curly braces} and their sub-message, and between the '=' and the number of an explicitValue.

There are 6 predefined case keywords in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and 'other'. You always have to define a message text for the default plural case "other" which is contained in every rule set. If you do not specify a message text for a particular plural case, the message text of the plural case "other" gets assigned to this plural case.

When formatting, the input number is first matched against the explicitValue clauses. If there is no exact-number match, then a keyword is selected by calling the PluralRules with the input number minus the offset. (The offset defaults to 0 if it is omitted from the pattern string.) If there is no clause with that keyword, then the "other" clauses is returned.

An unquoted pound sign (#) in the selected sub-message itself (i.e., outside of arguments nested in the sub-message) is replaced by the input number minus the offset. The number-minus-offset value is formatted using a NumberFormat for the PluralFormat's locale. If you need special number formatting, you have to use a MessageFormat and explicitly specify a NumberFormat argument. Note: That argument is formatting without subtracting the offset! If you need a custom format and have a non-zero offset, then you need to pass the number-minus-offset value as a separate parameter.

For a usage example, see the MessageFormat class documentation.

Defining Custom Plural Rules

If you need to use PluralFormat with custom rules, you can create a PluralRules object and pass it to PluralFormat's constructor. If you also specify a locale in this constructor, this locale will be used to format the number in the message texts.

For more information about PluralRules, see PluralRules.

Summary

Public constructors

PluralFormat()

Creates a new cardinal-number PluralFormat for the default FORMAT locale.

PluralFormat(ULocale ulocale)

Creates a new cardinal-number PluralFormat for a given locale.

PluralFormat(Locale locale)

Creates a new cardinal-number PluralFormat for a given Locale.

PluralFormat(PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules.

PluralFormat(ULocale ulocale, PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules.

PluralFormat(Locale locale, PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules.

PluralFormat(ULocale ulocale, PluralRules.PluralType type)

Creates a new PluralFormat for the plural type.

PluralFormat(Locale locale, PluralRules.PluralType type)

Creates a new PluralFormat for the plural type.

PluralFormat(String pattern)

Creates a new cardinal-number PluralFormat for a given pattern string.

PluralFormat(ULocale ulocale, String pattern)

Creates a new cardinal-number PluralFormat for a given pattern string and locale.

PluralFormat(PluralRules rules, String pattern)

Creates a new cardinal-number PluralFormat for a given set of rules and a pattern.

PluralFormat(ULocale ulocale, PluralRules rules, String pattern)

Creates a new cardinal-number PluralFormat for a given set of rules, a pattern and a locale.

PluralFormat(ULocale ulocale, PluralRules.PluralType type, String pattern)

Creates a new PluralFormat for a plural type, a pattern and a locale.

Public methods

void applyPattern(String pattern)

Sets the pattern used by this plural format.

boolean equals(Object rhs)

Indicates whether some other object is "equal to" this one.

boolean equals(PluralFormat rhs)

Returns true if this equals the provided PluralFormat.

final String format(double number)

Formats a plural message for a given number.

StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos)

Formats a plural message for a given number and appends the formatted message to the given StringBuffer.

int hashCode()

Returns a hash code value for the object.

Number parse(String text, ParsePosition parsePosition)

This method is not yet supported by PluralFormat.

Object parseObject(String source, ParsePosition pos)

This method is not yet supported by PluralFormat.

void setNumberFormat(NumberFormat format)

Sets the number format used by this formatter.

String toPattern()

Returns the pattern for this PluralFormat.

String toString()

Returns a string representation of the object.

Inherited methods

From class java.text.Format
From class java.lang.Object

Public constructors

PluralFormat

Added in API level 24
PluralFormat ()

Creates a new cardinal-number PluralFormat for the default FORMAT locale. This locale will be used to get the set of plural rules and for standard number formatting.

See also:

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale)

Creates a new cardinal-number PluralFormat for a given locale.

Parameters
ulocale ULocale: the PluralFormat will be configured with rules for this locale. This locale will also be used for standard number formatting.

PluralFormat

Added in API level 24
PluralFormat (Locale locale)

Creates a new cardinal-number PluralFormat for a given Locale.

Parameters
locale Locale: the PluralFormat will be configured with rules for this locale. This locale will also be used for standard number formatting.

PluralFormat

Added in API level 24
PluralFormat (PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules. The standard number formatting will be done using the default FORMAT locale.

Parameters
rules PluralRules: defines the behavior of the PluralFormat object.

See also:

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale, 
                PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules. The standard number formatting will be done using the given locale.

Parameters
ulocale ULocale: the default number formatting will be done using this locale.
rules PluralRules: defines the behavior of the PluralFormat object.

PluralFormat

Added in API level 24
PluralFormat (Locale locale, 
                PluralRules rules)

Creates a new cardinal-number PluralFormat for a given set of rules. The standard number formatting will be done using the given locale.

Parameters
locale Locale: the default number formatting will be done using this locale.
rules PluralRules: defines the behavior of the PluralFormat object.

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale, 
                PluralRules.PluralType type)

Creates a new PluralFormat for the plural type. The standard number formatting will be done using the given locale.

Parameters
ulocale ULocale: the default number formatting will be done using this locale.
type PluralRules.PluralType: The plural type (e.g., cardinal or ordinal).

PluralFormat

Added in API level 24
PluralFormat (Locale locale, 
                PluralRules.PluralType type)

Creates a new PluralFormat for the plural type. The standard number formatting will be done using the given Locale.

Parameters
locale Locale: the default number formatting will be done using this locale.
type PluralRules.PluralType: The plural type (e.g., cardinal or ordinal).

PluralFormat

Added in API level 24
PluralFormat (String pattern)

Creates a new cardinal-number PluralFormat for a given pattern string. The default FORMAT locale will be used to get the set of plural rules and for standard number formatting.

Parameters
pattern String: the pattern for this PluralFormat.
Throws
IllegalArgumentException if the pattern is invalid.

See also:

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale, 
                String pattern)

Creates a new cardinal-number PluralFormat for a given pattern string and locale. The locale will be used to get the set of plural rules and for standard number formatting.

Example code:

ULocale locEn = new ULocale("en");
ULocale locSl = new ULocale("sl");

String patEn = "one{dog} other{dogs}";                      // English 'dog'
String patSl = "one{pes} two{psa} few{psi} other{psov}";    // Slovenian translation of dog in Plural Form

// Create a new PluralFormat for a given locale locale and pattern string
PluralFormat plfmtEn = new PluralFormat(locEn, patEn);
PluralFormat plfmtSl = new PluralFormat(locSl, patSl);
// Constructs a MessageFormat for the specified locale and pattern.
MessageFormat msgfmtEn = new MessageFormat("{0,number} {1}", locEn);
MessageFormat msgfmtSl = new MessageFormat("{0,number} {1}", locSl);

final int[] numbers = {0, 1, 2, 3, 4, 5, 10, 100, 101, 102};
System.out.println("Output by using PluralFormat and MessageFormat API\n");
System.out.printf("%-16s%-16s%-16s\n", "Number", "English", "Slovenian");

// Use MessageFormat.format () to format the objects and appends to the given StringBuffer
for (int num : numbers) {
    StringBuffer msgEn = new StringBuffer();
    StringBuffer msgSl = new StringBuffer();

    msgfmtEn.format(new Object[] {num, plfmtEn.format(num)}, msgEn, new FieldPosition(0));
    msgfmtSl.format(new Object[] {num, plfmtSl.format(num)}, msgSl, new FieldPosition(0));

    System.out.printf("%-16s%-16s%-16s\n", num, msgEn, msgSl);
}

System.out.println();

// Equivalent code with message format pattern
String msgPatEn = "{0,plural, one{# dog} other{# dogs}}";
String msgPatSl = "{0,plural, one{# pes} two{# psa} few{# psi} other{# psov}}";

MessageFormat altMsgfmtEn = new MessageFormat(msgPatEn, locEn);
MessageFormat altMsgfmtSl = new MessageFormat(msgPatSl, locSl);
System.out.println("Same Output by using MessageFormat API only\n");
System.out.printf("%-16s%-16s%-16s\n", "Number", "English", "Slovenian");
for (int num : numbers) {
    StringBuffer msgEn = new StringBuffer();
    StringBuffer msgSl = new StringBuffer();

    altMsgfmtEn.format(new Object[] {num}, msgEn, new FieldPosition(0));
    altMsgfmtSl.format(new Object[] {num}, msgSl, new FieldPosition(0));

    System.out.printf("%-16s%-16s%-16s\n", num, msgEn, msgSl);
}
/** output of the sample code:
 ********************************************************************
  Number          English         Slovenian
  0               0 dogs          0 psov
  1               1 dog           1 pes
  2               2 dogs          2 psa
  3               3 dogs          3 psi
  4               4 dogs          4 psi
  5               5 dogs          5 psov
  10              10 dogs         10 psov
  100             100 dogs        100 psov
  101             101 dogs        101 pes
  102             102 dogs        102 psa

 *******************************************************************/

Parameters
ulocale ULocale: the PluralFormat will be configured with rules for this locale. This locale will also be used for standard number formatting.
pattern String: the pattern for this PluralFormat.
Throws
IllegalArgumentException if the pattern is invalid.

PluralFormat

Added in API level 24
PluralFormat (PluralRules rules, 
                String pattern)

Creates a new cardinal-number PluralFormat for a given set of rules and a pattern. The standard number formatting will be done using the default FORMAT locale.

Parameters
rules PluralRules: defines the behavior of the PluralFormat object.
pattern String: the pattern for this PluralFormat.
Throws
IllegalArgumentException if the pattern is invalid.

See also:

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale, 
                PluralRules rules, 
                String pattern)

Creates a new cardinal-number PluralFormat for a given set of rules, a pattern and a locale.

Parameters
ulocale ULocale: the PluralFormat will be configured with rules for this locale. This locale will also be used for standard number formatting.
rules PluralRules: defines the behavior of the PluralFormat object.
pattern String: the pattern for this PluralFormat.
Throws
IllegalArgumentException if the pattern is invalid.

PluralFormat

Added in API level 24
PluralFormat (ULocale ulocale, 
                PluralRules.PluralType type, 
                String pattern)

Creates a new PluralFormat for a plural type, a pattern and a locale.

Parameters
ulocale ULocale: the PluralFormat will be configured with rules for this locale. This locale will also be used for standard number formatting.
type PluralRules.PluralType: The plural type (e.g., cardinal or ordinal).
pattern String: the pattern for this PluralFormat.
Throws
IllegalArgumentException if the pattern is invalid.

Public methods

applyPattern

Added in API level 24
void applyPattern (String pattern)

Sets the pattern used by this plural format. The method parses the pattern and creates a map of format strings for the plural rules. Patterns and their interpretation are specified in the class description.

Parameters
pattern String: the pattern for this plural format.
Throws
IllegalArgumentException if the pattern is invalid.

equals

Added in API level 24
boolean equals (Object rhs)

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Parameters
rhs Object: the reference object with which to compare.
Returns
boolean true if this object is the same as the obj argument; false otherwise.

equals

Added in API level 24
boolean equals (PluralFormat rhs)

Returns true if this equals the provided PluralFormat.

Parameters
rhs PluralFormat: the PluralFormat to compare against
Returns
boolean true if this equals rhs

format

Added in API level 24
String format (double number)

Formats a plural message for a given number.

Parameters
number double: a number for which the plural message should be formatted. If no pattern has been applied to this PluralFormat object yet, the formatted number will be returned.
Returns
String the string containing the formatted plural message.

format

Added in API level 24
StringBuffer format (Object number, 
                StringBuffer toAppendTo, 
                FieldPosition pos)

Formats a plural message for a given number and appends the formatted message to the given StringBuffer.

Parameters
number Object: a number object (instance of Number for which the plural message should be formatted. If no pattern has been applied to this PluralFormat object yet, the formatted number will be returned. Note: If this object is not an instance of Number, the toAppendTo will not be modified.
toAppendTo StringBuffer: the formatted message will be appended to this StringBuffer.
pos FieldPosition: will be ignored by this method.
Returns
StringBuffer the string buffer passed in as toAppendTo, with formatted text appended.
Throws
IllegalArgumentException if number is not an instance of Number

hashCode

Added in API level 24
int hashCode ()

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Returns
int a hash code value for this object.

parse

Added in API level 24
Number parse (String text, 
                ParsePosition parsePosition)

This method is not yet supported by PluralFormat.

Parameters
text String: the string to be parsed.
parsePosition ParsePosition: defines the position where parsing is to begin, and upon return, the position where parsing left off. If the position has not changed upon return, then parsing failed.
Returns
Number nothing because this method is not yet implemented.
Throws
UnsupportedOperationException will always be thrown by this method.

parseObject

Added in API level 24
Object parseObject (String source, 
                ParsePosition pos)

This method is not yet supported by PluralFormat.

Parameters
source String: the string to be parsed.
pos ParsePosition: defines the position where parsing is to begin, and upon return, the position where parsing left off. If the position has not changed upon return, then parsing failed.
Returns
Object nothing because this method is not yet implemented.
Throws
UnsupportedOperationException will always be thrown by this method.

setNumberFormat

Added in API level 24
void setNumberFormat (NumberFormat format)

Sets the number format used by this formatter. You only need to call this if you want a different number format than the default formatter for the locale.

Parameters
format NumberFormat: the number format to use.

toPattern

Added in API level 24
String toPattern ()

Returns the pattern for this PluralFormat.

Returns
String the pattern string

toString

Added in API level 24
String toString ()

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 

Returns
String a string representation of the object.

Hooray!