Logo Search packages:      
Sourcecode: icu version File versions

ChoiceFormat Class Reference

#include <choicfmt.h>

Inheritance diagram for ChoiceFormat:

NumberFormat Format UObject UMemory

List of all members.


Detailed Description

ChoiceFormat converts between ranges of numeric values and string names for those ranges. A ChoiceFormat splits the real number line -Inf to +Inf into two or more contiguous ranges. Each range is mapped to a string. ChoiceFormat is generally used in a MessageFormat for displaying grammatically correct plurals such as "There are 2 files."

There are two methods of defining a ChoiceFormat; both are equivalent. The first is by using a string pattern. This is the preferred method in most cases. The second method is through direct specification of the arrays that make up the ChoiceFormat.

Patterns

In most cases, the preferred way to define a ChoiceFormat is with a pattern. Here is an example of a ChoiceFormat pattern:

    0≤are no files|1≤is one file|1<are many files

or equivalently,

    0#are no files|1#is one file|1<are many files

The pattern consists of a number or range specifiers separated by vertical bars '|' (U+007C). There is no vertical bar after the last range. Each range specifier is of the form:

Number Separator String

Number is a floating point number that can be parsed by a default NumberFormat for the US locale. It gives the lower limit of this range. The lower limit is either inclusive or exclusive, depending on the separator. The upper limit is given by the lower limit of the next range. The Unicode infinity sign ∞ (U+221E) is recognized for positive infinity. It may be preceded by '-' (U+002D) to indicate negative infinity.

String is the format string for this range, with special characters enclosed in single quotes ('The # sign'). Single quotes themselves are indicated by two single quotes in a row ('o''clock').

Separator is one of the following single characters:

See below for more information about closures.

Arrays

A ChoiceFormat defining n intervals (n >= 2) is specified by three arrays of n items:

Formatting and Parsing

During formatting, a number is converted to a string. ChoiceFormat accomplishes this by mapping the number to an interval using the following rule. Given a number X and and index value j in the range 0..n-1, where n is the number of ranges:

X matches j if and only if limit[j] <= X < limit[j+1]

(This assumes that all closures are FALSE. If some closures are TRUE then the relations must be changed to <= or < as appropriate.) If there is no match, then either the first or last index is used, depending on whether the number is too low or too high. Once a number is mapped to an interval j, the string formats[j] is output.

During parsing, a string is converted to a number. ChoiceFormat finds the element formats[j] equal to the string, and returns limits[j] as the parsed value.

Notes

The first limit value does not define a range boundary. For example, in the pattern "1.0#a|2.0#b", the intervals are [-Inf, 2.0) and [2.0, +Inf]. It appears that the first interval should be [1.0, 2.0). However, since all values that are too small are mapped to range zero, the first interval is effectively [-Inf, 2.0). However, the first limit value is used during formatting. In this example, parse("a") returns 1.0.

There are no gaps between intervals and the entire number line is covered. A ChoiceFormat maps all possible double values to a finite set of intervals.

The non-number NaN is mapped to interval zero during formatting.

Examples

Here is an example of two arrays that map the number 1..7 to the English day of the week abbreviations Sun..Sat. No closures array is given; this is the same as specifying all closures to be FALSE.

    {1,2,3,4,5,6,7},
     {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}

Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1, +Inf] to three strings. That is, the number line is split into three ranges: x < 1.0, x = 1.0, and x > 1.0.

    {0, 1, 1},
     {FALSE, FALSE, TRUE},
     {"no files", "one file", "many files"}

Here is a simple example that shows formatting and parsing:

   #include <unicode/choicfmt.h>
   #include <unicode/unistr.h>
   #include <iostream.h>
   
   int main(int argc, char *argv[]) {
       double limits[] = {1,2,3,4,5,6,7};
       UnicodeString monthNames[] = {
           "Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
       ChoiceFormat fmt(limits, monthNames, 7);
       UnicodeString str;
       char buf[256];
       for (double x = 1.0; x <= 8.0; x += 1.0) {
           fmt.format(x, str);
           str.extract(0, str.length(), buf, 256, "");
           str.truncate(0);
           cout << x << " -> "
                << buf << endl;
       }
       cout << endl;
       return 0;
   }

Here is a more complex example using a ChoiceFormat constructed from a pattern together with a MessageFormat.

   #include <unicode/choicfmt.h>
   #include <unicode/msgfmt.h>
   #include <unicode/unistr.h>
   #include <iostream.h>
 
   int main(int argc, char *argv[]) {
       UErrorCode status = U_ZERO_ERROR;
       double filelimits[] = {0,1,2};
       UnicodeString filepart[] =
           {"are no files","is one file","are {0} files"};
       ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3 );
       Format* testFormats[] =
           {fileform, NULL, NumberFormat::createInstance(status)};
       MessageFormat pattform("There {0} on {1}", status );
       pattform.adoptFormats(testFormats, 3);
       Formattable testArgs[] = {0L, "Disk A"};
       FieldPosition fp(0);
       UnicodeString str;
       char buf[256];
       for (int32_t i = 0; i < 4; ++i) {
           Formattable fInt(i);
           testArgs[0] = fInt;
           pattform.format(testArgs, 2, str, fp, status );
           str.extract(0, str.length(), buf, "");
           str.truncate(0);
           cout << "Output for i=" << i << " : " << buf << endl;
       }
       cout << endl;
       return 0;
   }

User subclasses are not supported. While clients may write subclasses, such code will not necessarily work and will not be guaranteed to work stably from release to release.

Definition at line 259 of file choicfmt.h.


Public Types

enum  EAlignmentFields { kIntegerField, kFractionField, INTEGER_FIELD = kIntegerField, FRACTION_FIELD = kFractionField }
enum  EStyles {
  kNumberStyle, kCurrencyStyle, kPercentStyle, kScientificStyle,
  kIsoCurrencyStyle, kPluralCurrencyStyle, kStyleCount
}

Public Member Functions

virtual void applyPattern (const UnicodeString &pattern, UParseError &parseError, UErrorCode &status)
virtual void applyPattern (const UnicodeString &pattern, UErrorCode &status)
 ChoiceFormat (const ChoiceFormat &that)
 ChoiceFormat (const double *limits, const UBool *closures, const UnicodeString *formats, int32_t count)
 ChoiceFormat (const double *limits, const UnicodeString *formats, int32_t count)
 ChoiceFormat (const UnicodeString &pattern, UErrorCode &status)
virtual Formatclone (void) const
UnicodeStringformat (int64_t number, UnicodeString &appendTo) const
UnicodeStringformat (int32_t number, UnicodeString &appendTo) const
UnicodeStringformat (double number, UnicodeString &appendTo) const
UnicodeStringformat (const Formattable &obj, UnicodeString &appendTo, UErrorCode &status) const
virtual UnicodeStringformat (const Formattable &obj, UnicodeString &appendTo, FieldPosition &pos, UErrorCode &status) const
virtual UnicodeStringformat (const Formattable *objs, int32_t cnt, UnicodeString &appendTo, FieldPosition &pos, UErrorCode &success) const
virtual UnicodeStringformat (int64_t number, UnicodeString &appendTo, FieldPosition &pos) const
virtual UnicodeStringformat (int32_t number, UnicodeString &appendTo, FieldPosition &pos) const
virtual UnicodeStringformat (double number, UnicodeString &appendTo, FieldPosition &pos) const
virtual const UBoolgetClosures (int32_t &count) const
const UChar * getCurrency () const
virtual UClassID getDynamicClassID (void) const
virtual const UnicodeStringgetFormats (int32_t &count) const
virtual const double * getLimits (int32_t &count) const
Locale getLocale (ULocDataLocaleType type, UErrorCode &status) const
const char * getLocaleID (ULocDataLocaleType type, UErrorCode &status) const
int32_t getMaximumFractionDigits (void) const
int32_t getMaximumIntegerDigits (void) const
int32_t getMinimumFractionDigits (void) const
int32_t getMinimumIntegerDigits (void) const
UBool isGroupingUsed (void) const
UBool isParseIntegerOnly (void) const
UBool operator!= (const Format &other) const
const ChoiceFormatoperator= (const ChoiceFormat &that)
virtual UBool operator== (const Format &other) const
virtual void parse (const UnicodeString &text, Formattable &result, UErrorCode &status) const
virtual void parse (const UnicodeString &text, Formattable &result, ParsePosition &parsePosition) const
virtual FormattableparseCurrency (const UnicodeString &text, Formattable &result, ParsePosition &pos) const
void parseObject (const UnicodeString &source, Formattable &result, UErrorCode &status) const
virtual void parseObject (const UnicodeString &source, Formattable &result, ParsePosition &parse_pos) const
virtual void setChoices (const double *limits, const UBool *closures, const UnicodeString *formats, int32_t count)
virtual void setChoices (const double *limitsToCopy, const UnicodeString *formatsToCopy, int32_t count)
virtual void setCurrency (const UChar *theCurrency, UErrorCode &ec)
virtual void setGroupingUsed (UBool newValue)
virtual void setMaximumFractionDigits (int32_t newValue)
virtual void setMaximumIntegerDigits (int32_t newValue)
virtual void setMinimumFractionDigits (int32_t newValue)
virtual void setMinimumIntegerDigits (int32_t newValue)
virtual void setParseIntegerOnly (UBool value)
virtual UnicodeStringtoPattern (UnicodeString &pattern) const
virtual ~ChoiceFormat ()

Static Public Member Functions

static NumberFormat *U_EXPORT2 createCurrencyInstance (const Locale &inLocale, UErrorCode &)
static NumberFormat *U_EXPORT2 createCurrencyInstance (UErrorCode &)
static NumberFormat *U_EXPORT2 createInstance (const Locale &desiredLocale, EStyles choice, UErrorCode &success)
static NumberFormat *U_EXPORT2 createInstance (const Locale &inLocale, UErrorCode &)
static NumberFormat *U_EXPORT2 createInstance (UErrorCode &)
static NumberFormat *U_EXPORT2 createPercentInstance (const Locale &inLocale, UErrorCode &)
static NumberFormat *U_EXPORT2 createPercentInstance (UErrorCode &)
static NumberFormat *U_EXPORT2 createScientificInstance (const Locale &inLocale, UErrorCode &)
static NumberFormat *U_EXPORT2 createScientificInstance (UErrorCode &)
static StringEnumeration *U_EXPORT2 getAvailableLocales (void)
static const Locale *U_EXPORT2 getAvailableLocales (int32_t &count)
static UClassID U_EXPORT2 getStaticClassID (void)
static void U_EXPORT2 operator delete (void *, void *) U_NO_THROW
static void U_EXPORT2 operator delete (void *p) U_NO_THROW
static void U_EXPORT2 operator delete[] (void *p) U_NO_THROW
static void *U_EXPORT2 operator new (size_t, void *ptr) U_NO_THROW
static void *U_EXPORT2 operator new (size_t size) U_NO_THROW
static void *U_EXPORT2 operator new[] (size_t size) U_NO_THROW
static URegistryKey U_EXPORT2 registerFactory (NumberFormatFactory *toAdopt, UErrorCode &status)
static UBool U_EXPORT2 unregister (URegistryKey key, UErrorCode &status)

Protected Member Functions

virtual void getEffectiveCurrency (UChar *result, UErrorCode &ec) const
void setLocaleIDs (const char *valid, const char *actual)

Static Protected Member Functions

static void syntaxError (const UnicodeString &pattern, int32_t pos, UParseError &parseError)

Private Member Functions

 ChoiceFormat (const UnicodeString &newPattern, UParseError &parseError, UErrorCode &status)

Static Private Member Functions

static UnicodeStringdtos (double value, UnicodeString &string)
static double stod (const UnicodeString &string)

Private Attributes

UnicodeStringfChoiceFormats
double * fChoiceLimits
UBoolfClosures
int32_t fCount

Friends

class MessageFormat

The documentation for this class was generated from the following files:

Generated by  Doxygen 1.6.0   Back to index