1 /*
2 *******************************************************************************
3 * Copyright (C) 1997-2006, International Business Machines Corporation and others.
4 * All Rights Reserved.
5 *******************************************************************************
6 */
7
8 #ifndef RBNF_H
9 #define RBNF_H
10
11 #include "unicode/utypes.h"
12
13 /**
14 * \file
15 * \brief C++ API: Rule Based Number Format
16 */
17
18 /**
19 * \def U_HAVE_RBNF
20 * This will be 0 if RBNF support is not included in ICU
21 * and 1 if it is.
22 *
23 * @stable ICU 2.4
24 */
25 #if UCONFIG_NO_FORMATTING
26 #define U_HAVE_RBNF 0
27 #else
28 #define U_HAVE_RBNF 1
29
30 #include "unicode/coll.h"
31 #include "unicode/dcfmtsym.h"
32 #include "unicode/fmtable.h"
33 #include "unicode/locid.h"
34 #include "unicode/numfmt.h"
35 #include "unicode/unistr.h"
36 #include "unicode/strenum.h"
37
38 U_NAMESPACE_BEGIN
39
40 class NFRuleSet;
41 class LocalizationInfo;
42
43 /**
44 * Tags for the predefined rulesets.
45 *
46 * @stable ICU 2.2
47 */
48 enum URBNFRuleSetTag {
49 URBNF_SPELLOUT,
50 URBNF_ORDINAL,
51 URBNF_DURATION,
52 URBNF_COUNT
53 };
54
55 #if UCONFIG_NO_COLLATION
56 class Collator;
57 #endif
58
59 /**
60 * The RuleBasedNumberFormat class formats numbers according to a set of rules. This number formatter is
61 * typically used for spelling out numeric values in words (e.g., 25,3476 as
62 * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois
63 * cents soixante-seize" or
64 * "fünfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for
65 * other complicated formatting tasks, such as formatting a number of seconds as hours,
66 * minutes and seconds (e.g., 3,730 as "1:02:10").
67 *
68 * <p>The resources contain three predefined formatters for each locale: spellout, which
69 * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which
70 * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and
71 * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is
72 * "2:03"). The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s
73 * by supplying programmer-defined rule sets.</p>
74 *
75 * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description
76 * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource
77 * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>
78 * Each rule has a string of output text and a value or range of values it is applicable to.
79 * In a typical spellout rule set, the first twenty rules are the words for the numbers from
80 * 0 to 19:</p>
81 *
82 * <pre>zero; one; two; three; four; five; six; seven; eight; nine;
83 * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>
84 *
85 * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and
86 * we only have to supply the words for the multiples of 10:</p>
87 *
88 * <pre> 20: twenty[->>];
89 * 30: thirty[->>];
90 * 40: forty[->>];
91 * 50: fifty[->>];
92 * 60: sixty[->>];
93 * 70: seventy[->>];
94 * 80: eighty[->>];
95 * 90: ninety[->>];</pre>
96 *
97 * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the
98 * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable
99 * to all numbers from its own base value to one less than the next rule's base value. The
100 * ">>" token is called a <em>substitution</em> and tells the fomatter to
101 * isolate the number's ones digit, format it using this same set of rules, and place the
102 * result at the position of the ">>" token. Text in brackets is omitted if
103 * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24
104 * is "twenty-four," not "twenty four").</p>
105 *
106 * <p>For even larger numbers, we can actually look up several parts of the number in the
107 * list:</p>
108 *
109 * <pre>100: << hundred[ >>];</pre>
110 *
111 * <p>The "<<" represents a new kind of substitution. The << isolates
112 * the hundreds digit (and any digits to its left), formats it using this same rule set, and
113 * places the result where the "<<" was. Notice also that the meaning of
114 * >> has changed: it now refers to both the tens and the ones digits. The meaning of
115 * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>
116 * which is the highest power of 10 that is less than or equal to the base value (the user
117 * can change this). To fill in the substitutions, the formatter divides the number being
118 * formatted by the divisor. The integral quotient is used to fill in the <<
119 * substitution, and the remainder is used to fill in the >> substitution. The meaning
120 * of the brackets changes similarly: text in brackets is omitted if the value being
121 * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so
122 * if a substitution is filled in with text that includes another substitution, that
123 * substitution is also filled in.</p>
124 *
125 * <p>This rule covers values up to 999, at which point we add another rule:</p>
126 *
127 * <pre>1000: << thousand[ >>];</pre>
128 *
129 * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's
130 * base value is a higher power of 10, changing the rule's divisor. This rule can actually be
131 * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>
132 *
133 * <pre> 1,000,000: << million[ >>];
134 * 1,000,000,000: << billion[ >>];
135 * 1,000,000,000,000: << trillion[ >>];
136 * 1,000,000,000,000,000: OUT OF RANGE!;</pre>
137 *
138 * <p>Commas, periods, and spaces can be used in the base values to improve legibility and
139 * are ignored by the rule parser. The last rule in the list is customarily treated as an
140 * "overflow rule," applying to everything from its base value on up, and often (as
141 * in this example) being used to print out an error message or default representation.
142 * Notice also that the size of the major groupings in large numbers is controlled by the
143 * spacing of the rules: because in English we group numbers by thousand, the higher rules
144 * are separated from each other by a factor of 1,000.</p>
145 *
146 * <p>To see how these rules actually work in practice, consider the following example:
147 * Formatting 25,430 with this rule set would work like this:</p>
148 *
149 * <table border="0" width="100%">
150 * <tr>
151 * <td><strong><< thousand >></strong></td>
152 * <td>[the rule whose base value is 1,000 is applicable to 25,340]</td>
153 * </tr>
154 * <tr>
155 * <td><strong>twenty->></strong> thousand >></td>
156 * <td>[25,340 over 1,000 is 25. The rule for 20 applies.]</td>
157 * </tr>
158 * <tr>
159 * <td>twenty-<strong>five</strong> thousand >></td>
160 * <td>[25 mod 10 is 5. The rule for 5 is "five."</td>
161 * </tr>
162 * <tr>
163 * <td>twenty-five thousand <strong><< hundred >></strong></td>
164 * <td>[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>
165 * </tr>
166 * <tr>
167 * <td>twenty-five thousand <strong>three</strong> hundred >></td>
168 * <td>[340 over 100 is 3. The rule for 3 is "three."]</td>
169 * </tr>
170 * <tr>
171 * <td>twenty-five thousand three hundred <strong>forty</strong></td>
172 * <td>[340 mod 100 is 40. The rule for 40 applies. Since 40 divides
173 * evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>
174 * </tr>
175 * </table>
176 *
177 * <p>The above syntax suffices only to format positive integers. To format negative numbers,
178 * we add a special rule:</p>
179 *
180 * <pre>-x: minus >>;</pre>
181 *
182 * <p>This is called a <em>negative-number rule,</em> and is identified by "-x"
183 * where the base value would be. This rule is used to format all negative numbers. the
184 * >> token here means "find the number's absolute value, format it with these
185 * rules, and put the result here."</p>
186 *
187 * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional
188 * parts:</p>
189 *
190 * <pre>x.x: << point >>;</pre>
191 *
192 * <p>This rule is used for all positive non-integers (negative non-integers pass through the
193 * negative-number rule first and then through this rule). Here, the << token refers to
194 * the number's integral part, and the >> to the number's fractional part. The
195 * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be
196 * formatted as "one hundred twenty-three point four five six").</p>
197 *
198 * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>
199 *
200 * <p>There is actually much more flexibility built into the rule language than the
201 * description above shows. A formatter may own multiple rule sets, which can be selected by
202 * the caller, and which can use each other to fill in their substitutions. Substitutions can
203 * also be filled in with digits, using a DecimalFormat object. There is syntax that can be
204 * used to alter a rule's divisor in various ways. And there is provision for much more
205 * flexible fraction handling. A complete description of the rule syntax follows:</p>
206 *
207 * <hr>
208 *
209 * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule
210 * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule
211 * set name must begin with a % sign. Rule sets with names that begin with a single % sign
212 * are <em>public:</em> the caller can specify that they be used to format and parse numbers.
213 * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use
214 * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>
215 *
216 * <p>The user can also specify a special "rule set" named <tt>%%lenient-parse</tt>.
217 * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>
218 * description which is used to define equivalences for lenient parsing. For more information
219 * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,
220 * see <tt>setLenientParse()</tt>. <em>Note:</em> symbols that have syntactic meaning
221 * in collation rules, such as '&', have no particular meaning when appearing outside
222 * of the <tt>lenient-parse</tt> rule set.</p>
223 *
224 * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>
225 * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>
226 * These parameters are controlled by the description syntax, which consists of a <em>rule
227 * descriptor,</em> a colon, and a <em>rule body.</em></p>
228 *
229 * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the
230 * name of a token):</p>
231 *
232 * <table border="0" width="100%">
233 * <tr>
234 * <td><em>bv</em>:</td>
235 * <td><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal
236 * number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,
237 * which are ignored. The rule's divisor is the highest power of 10 less than or equal to
238 * the base value.</td>
239 * </tr>
240 * <tr>
241 * <td><em>bv</em>/<em>rad</em>:</td>
242 * <td><em>bv</em> specifies the rule's base value. The rule's divisor is the
243 * highest power of <em>rad</em> less than or equal to the base value.</td>
244 * </tr>
245 * <tr>
246 * <td><em>bv</em>>:</td>
247 * <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
248 * let the radix be 10, and the exponent be the highest exponent of the radix that yields a
249 * result less than or equal to the base value. Every > character after the base value
250 * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
251 * raised to the power of the exponent; otherwise, the divisor is 1.</td>
252 * </tr>
253 * <tr>
254 * <td><em>bv</em>/<em>rad</em>>:</td>
255 * <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
256 * let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that
257 * yields a result less than or equal to the base value. Every > character after the radix
258 * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
259 * raised to the power of the exponent; otherwise, the divisor is 1.</td>
260 * </tr>
261 * <tr>
262 * <td>-x:</td>
263 * <td>The rule is a negative-number rule.</td>
264 * </tr>
265 * <tr>
266 * <td>x.x:</td>
267 * <td>The rule is an <em>improper fraction rule.</em></td>
268 * </tr>
269 * <tr>
270 * <td>0.x:</td>
271 * <td>The rule is a <em>proper fraction rule.</em></td>
272 * </tr>
273 * <tr>
274 * <td>x.0:</td>
275 * <td>The rule is a <em>master rule.</em></td>
276 * </tr>
277 * <tr>
278 * <td><em>nothing</em></td>
279 * <td>If the rule's rule descriptor is left out, the base value is one plus the
280 * preceding rule's base value (or zero if this is the first rule in the list) in a normal
281 * rule set. In a fraction rule set, the base value is the same as the preceding rule's
282 * base value.</td>
283 * </tr>
284 * </table>
285 *
286 * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending
287 * on whether it is used to format a number's integral part (or the whole number) or a
288 * number's fractional part. Using a rule set to format a rule's fractional part makes it a
289 * fraction rule set.</p>
290 *
291 * <p>Which rule is used to format a number is defined according to one of the following
292 * algorithms: If the rule set is a regular rule set, do the following:
293 *
294 * <ul>
295 * <li>If the rule set includes a master rule (and the number was passed in as a <tt>double</tt>),
296 * use the master rule. (If the number being formatted was passed in as a <tt>long</tt>,
297 * the master rule is ignored.)</li>
298 * <li>If the number is negative, use the negative-number rule.</li>
299 * <li>If the number has a fractional part and is greater than 1, use the improper fraction
300 * rule.</li>
301 * <li>If the number has a fractional part and is between 0 and 1, use the proper fraction
302 * rule.</li>
303 * <li>Binary-search the rule list for the rule with the highest base value less than or equal
304 * to the number. If that rule has two substitutions, its base value is not an even multiple
305 * of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the
306 * rule that precedes it in the rule list. Otherwise, use the rule itself.</li>
307 * </ul>
308 *
309 * <p>If the rule set is a fraction rule set, do the following:
310 *
311 * <ul>
312 * <li>Ignore negative-number and fraction rules.</li>
313 * <li>For each rule in the list, multiply the number being formatted (which will always be
314 * between 0 and 1) by the rule's base value. Keep track of the distance between the result
315 * the nearest integer.</li>
316 * <li>Use the rule that produced the result closest to zero in the above calculation. In the
317 * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is
318 * to try each rule's base value as a possible denominator of a fraction. Whichever
319 * denominator produces the fraction closest in value to the number being formatted wins.) If
320 * the rule following the matching rule has the same base value, use it if the numerator of
321 * the fraction is anything other than 1; if the numerator is 1, use the original matching
322 * rule. (This is to allow singular and plural forms of the rule text without a lot of extra
323 * hassle.)</li>
324 * </ul>
325 *
326 * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule
327 * may include zero, one, or two <em>substitution tokens,</em> and a range of text in
328 * brackets. The brackets denote optional text (and may also include one or both
329 * substitutions). The exact meanings of the substitution tokens, and under what conditions
330 * optional text is omitted, depend on the syntax of the substitution token and the context.
331 * The rest of the text in a rule body is literal text that is output when the rule matches
332 * the number being formatted.</p>
333 *
334 * <p>A substitution token begins and ends with a <em>token character.</em> The token
335 * character and the context together specify a mathematical operation to be performed on the
336 * number being formatted. An optional <em>substitution descriptor </em>specifies how the
337 * value resulting from that operation is used to fill in the substitution. The position of
338 * the substitution token in the rule body specifies the location of the resultant text in
339 * the original rule text.</p>
340 *
341 * <p>The meanings of the substitution token characters are as follows:</p>
342 *
343 * <table border="0" width="100%">
344 * <tr>
345 * <td>>></td>
346 * <td>in normal rule</td>
347 * <td>Divide the number by the rule's divisor and format the remainder</td>
348 * </tr>
349 * <tr>
350 * <td></td>
351 * <td>in negative-number rule</td>
352 * <td>Find the absolute value of the number and format the result</td>
353 * </tr>
354 * <tr>
355 * <td></td>
356 * <td>in fraction or master rule</td>
357 * <td>Isolate the number's fractional part and format it.</td>
358 * </tr>
359 * <tr>
360 * <td></td>
361 * <td>in rule in fraction rule set</td>
362 * <td>Not allowed.</td>
363 * </tr>
364 * <tr>
365 * <td>>>></td>
366 * <td>in normal rule</td>
367 * <td>Divide the number by the rule's divisor and format the remainder,
368 * but bypass the normal rule-selection process and just use the
369 * rule that precedes this one in this rule list.</td>
370 * </tr>
371 * <tr>
372 * <td></td>
373 * <td>in all other rules</td>
374 * <td>Not allowed.</td>
375 * </tr>
376 * <tr>
377 * <td><<</td>
378 * <td>in normal rule</td>
379 * <td>Divide the number by the rule's divisor and format the quotient</td>
380 * </tr>
381 * <tr>
382 * <td></td>
383 * <td>in negative-number rule</td>
384 * <td>Not allowed.</td>
385 * </tr>
386 * <tr>
387 * <td></td>
388 * <td>in fraction or master rule</td>
389 * <td>Isolate the number's integral part and format it.</td>
390 * </tr>
391 * <tr>
392 * <td></td>
393 * <td>in rule in fraction rule set</td>
394 * <td>Multiply the number by the rule's base value and format the result.</td>
395 * </tr>
396 * <tr>
397 * <td>==</td>
398 * <td>in all rule sets</td>
399 * <td>Format the number unchanged</td>
400 * </tr>
401 * <tr>
402 * <td>[]</td>
403 * <td>in normal rule</td>
404 * <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>
405 * </tr>
406 * <tr>
407 * <td></td>
408 * <td>in negative-number rule</td>
409 * <td>Not allowed.</td>
410 * </tr>
411 * <tr>
412 * <td></td>
413 * <td>in improper-fraction rule</td>
414 * <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an
415 * x.x rule and a 0.x rule)</td>
416 * </tr>
417 * <tr>
418 * <td></td>
419 * <td>in master rule</td>
420 * <td>Omit the optional text if the number is an integer (same as specifying both an x.x
421 * rule and an x.0 rule)</td>
422 * </tr>
423 * <tr>
424 * <td></td>
425 * <td>in proper-fraction rule</td>
426 * <td>Not allowed.</td>
427 * </tr>
428 * <tr>
429 * <td></td>
430 * <td>in rule in fraction rule set</td>
431 * <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>
432 * </tr>
433 * </table>
434 *
435 * <p>The substitution descriptor (i.e., the text between the token characters) may take one
436 * of three forms:</p>
437 *
438 * <table border="0" width="100%">
439 * <tr>
440 * <td>a rule set name</td>
441 * <td>Perform the mathematical operation on the number, and format the result using the
442 * named rule set.</td>
443 * </tr>
444 * <tr>
445 * <td>a DecimalFormat pattern</td>
446 * <td>Perform the mathematical operation on the number, and format the result using a
447 * DecimalFormat with the specified pattern. The pattern must begin with 0 or #.</td>
448 * </tr>
449 * <tr>
450 * <td>nothing</td>
451 * <td>Perform the mathematical operation on the number, and format the result using the rule
452 * set containing the current rule, except:
453 * <ul>
454 * <li>You can't have an empty substitution descriptor with a == substitution.</li>
455 * <li>If you omit the substitution descriptor in a >> substitution in a fraction rule,
456 * format the result one digit at a time using the rule set containing the current rule.</li>
457 * <li>If you omit the substitution descriptor in a << substitution in a rule in a
458 * fraction rule set, format the result using the default rule set for this formatter.</li>
459 * </ul>
460 * </td>
461 * </tr>
462 * </table>
463 *
464 * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule
465 * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,
466 * the apostrophe is ignored, but all text after it becomes significant (this is how you can
467 * have a rule's rule text begin with whitespace). There is no escape function: the semicolon
468 * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set
469 * names. The characters beginning a substitution token are always treated as the beginning
470 * of a substitution token.</p>
471 *
472 * <p>See the resource data and the demo program for annotated examples of real rule sets
473 * using these features.</p>
474 *
475 * <p><em>User subclasses are not supported.</em> While clients may write
476 * subclasses, such code will not necessarily work and will not be
477 * guaranteed to work stably from release to release.
478 *
479 * <p><b>Localizations</b></p>
480 * <p>Constructors are available that allow the specification of localizations for the
481 * public rule sets (and also allow more control over what public rule sets are available).
482 * Localization data is represented as a textual description. The description represents
483 * an array of arrays of string. The first element is an array of the public rule set names,
484 * each of these must be one of the public rule set names that appear in the rules. Only
485 * names in this array will be treated as public rule set names by the API. Each subsequent
486 * element is an array of localizations of these names. The first element of one of these
487 * subarrays is the locale name, and the remaining elements are localizations of the
488 * public rule set names, in the same order as they were listed in the first arrray.</p>
489 * <p>In the syntax, angle brackets '<', '>' are used to delimit the arrays, and comma ',' is used
490 * to separate elements of an array. Whitespace is ignored, unless quoted.</p>
491 * <p>For example:<pre>
492 * < < %foo, %bar, %baz >,
493 * < en, Foo, Bar, Baz >,
494 * < fr, 'le Foo', 'le Bar', 'le Baz' >
495 * < zh, \\u7532, \\u4e59, \\u4e19 > >
496 * </pre></p>
497 * @author Richard Gillam
498 * @see NumberFormat
499 * @see DecimalFormat
500 * @stable ICU 2.0
501 */
502 class U_I18N_API RuleBasedNumberFormat : public NumberFormat {
503 public:
504
505 //-----------------------------------------------------------------------
506 // constructors
507 //-----------------------------------------------------------------------
508
509 /**
510 * Creates a RuleBasedNumberFormat that behaves according to the description
511 * passed in. The formatter uses the default locale.
512 * @param rules A description of the formatter's desired behavior.
513 * See the class documentation for a complete explanation of the description
514 * syntax.
515 * @param perror The parse error if an error was encountered.
516 * @param status The status indicating whether the constructor succeeded.
517 * @stable ICU 3.2
518 */
519 RuleBasedNumberFormat(const UnicodeString& rules, UParseError& perror, UErrorCode& status);
520
521 /**
522 * Creates a RuleBasedNumberFormat that behaves according to the description
523 * passed in. The formatter uses the default locale.
524 * <p>
525 * The localizations data provides information about the public
526 * rule sets and their localized display names for different
527 * locales. The first element in the list is an array of the names
528 * of the public rule sets. The first element in this array is
529 * the initial default ruleset. The remaining elements in the
530 * list are arrays of localizations of the names of the public
531 * rule sets. Each of these is one longer than the initial array,
532 * with the first String being the ULocale ID, and the remaining
533 * Strings being the localizations of the rule set names, in the
534 * same order as the initial array. Arrays are NULL-terminated.
535 * @param rules A description of the formatter's desired behavior.
536 * See the class documentation for a complete explanation of the description
537 * syntax.
538 * @param localizations the localization information.
539 * names in the description. These will be copied by the constructor.
540 * @param perror The parse error if an error was encountered.
541 * @param status The status indicating whether the constructor succeeded.
542 * @stable ICU 3.2
543 */
544 RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
545 UParseError& perror, UErrorCode& status);
546
547 /**
548 * Creates a RuleBasedNumberFormat that behaves according to the rules
549 * passed in. The formatter uses the specified locale to determine the
550 * characters to use when formatting numerals, and to define equivalences
551 * for lenient parsing.
552 * @param rules The formatter rules.
553 * See the class documentation for a complete explanation of the rule
554 * syntax.
555 * @param locale A locale that governs which characters are used for
556 * formatting values in numerals and which characters are equivalent in
557 * lenient parsing.
558 * @param perror The parse error if an error was encountered.
559 * @param status The status indicating whether the constructor succeeded.
560 * @stable ICU 2.0
561 */
562 RuleBasedNumberFormat(const UnicodeString& rules, const Locale& locale,
563 UParseError& perror, UErrorCode& status);
564
565 /**
566 * Creates a RuleBasedNumberFormat that behaves according to the description
567 * passed in. The formatter uses the default locale.
568 * <p>
569 * The localizations data provides information about the public
570 * rule sets and their localized display names for different
571 * locales. The first element in the list is an array of the names
572 * of the public rule sets. The first element in this array is
573 * the initial default ruleset. The remaining elements in the
574 * list are arrays of localizations of the names of the public
575 * rule sets. Each of these is one longer than the initial array,
576 * with the first String being the ULocale ID, and the remaining
577 * Strings being the localizations of the rule set names, in the
578 * same order as the initial array. Arrays are NULL-terminated.
579 * @param rules A description of the formatter's desired behavior.
580 * See the class documentation for a complete explanation of the description
581 * syntax.
582 * @param localizations a list of localizations for the rule set
583 * names in the description. These will be copied by the constructor.
584 * @param locale A locale that governs which characters are used for
585 * formatting values in numerals and which characters are equivalent in
586 * lenient parsing.
587 * @param perror The parse error if an error was encountered.
588 * @param status The status indicating whether the constructor succeeded.
589 * @stable ICU 3.2
590 */
591 RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
592 const Locale& locale, UParseError& perror, UErrorCode& status);
593
594 /**
595 * Creates a RuleBasedNumberFormat from a predefined ruleset. The selector
596 * code choosed among three possible predefined formats: spellout, ordinal,
597 * and duration.
598 * @param tag A selector code specifying which kind of formatter to create for that
599 * locale. There are three legal values: URBNF_SPELLOUT, which creates a formatter that
600 * spells out a value in words in the desired language, URBNF_ORDINAL, which attaches
601 * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
602 * and URBNF_DURATION, which formats a duration in seconds as hours, minutes, and seconds.
603 * @param locale The locale for the formatter.
604 * @param status The status indicating whether the constructor succeeded.
605 * @stable ICU 2.0
606 */
607 RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& locale, UErrorCode& status);
608
609 //-----------------------------------------------------------------------
610 // boilerplate
611 //-----------------------------------------------------------------------
612
613 /**
614 * Copy constructor
615 * @param rhs the object to be copied from.
616 * @stable ICU 2.6
617 */
618 RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs);
619
620 /**
621 * Assignment operator
622 * @param rhs the object to be copied from.
623 * @stable ICU 2.6
624 */
625 RuleBasedNumberFormat& operator=(const RuleBasedNumberFormat& rhs);
626
627 /**
628 * Release memory allocated for a RuleBasedNumberFormat when you are finished with it.
629 * @stable ICU 2.6
630 */
631 virtual ~RuleBasedNumberFormat();
632
633 /**
634 * Clone this object polymorphically. The caller is responsible
635 * for deleting the result when done.
636 * @return A copy of the object.
637 * @stable ICU 2.6
638 */
639 virtual Format* clone(void) const;
640
641 /**
642 * Return true if the given Format objects are semantically equal.
643 * Objects of different subclasses are considered unequal.
644 * @param other the object to be compared with.
645 * @return true if the given Format objects are semantically equal.
646 * @stable ICU 2.6
647 */
648 virtual UBool operator==(const Format& other) const;
649
650 //-----------------------------------------------------------------------
651 // public API functions
652 //-----------------------------------------------------------------------
653
654 /**
655 * return the rules that were provided to the RuleBasedNumberFormat.
656 * @return the result String that was passed in
657 * @stable ICU 2.0
658 */
659 virtual UnicodeString getRules() const;
660
661 /**
662 * Return the number of public rule set names.
663 * @return the number of public rule set names.
664 * @stable ICU 2.0
665 */
666 virtual int32_t getNumberOfRuleSetNames() const;
667
668 /**
669 * Return the name of the index'th public ruleSet. If index is not valid,
670 * the function returns null.
671 * @param index the index of the ruleset
672 * @return the name of the index'th public ruleSet.
673 * @stable ICU 2.0
674 */
675 virtual UnicodeString getRuleSetName(int32_t index) const;
676
677 /**
678 * Return the number of locales for which we have localized rule set display names.
679 * @return the number of locales for which we have localized rule set display names.
680 * @stable ICU 3.2
681 */
682 virtual int32_t getNumberOfRuleSetDisplayNameLocales(void) const;
683
684 /**
685 * Return the index'th display name locale.
686 * @param index the index of the locale
687 * @param status set to a failure code when this function fails
688 * @return the locale
689 * @see #getNumberOfRuleSetDisplayNameLocales
690 * @stable ICU 3.2
691 */
692 virtual Locale getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const;
693
694 /**
695 * Return the rule set display names for the provided locale. These are in the same order
696 * as those returned by getRuleSetName. The locale is matched against the locales for
697 * which there is display name data, using normal fallback rules. If no locale matches,
698 * the default display names are returned. (These are the internal rule set names minus
699 * the leading '%'.)
700 * @param index the index of the rule set
701 * @param locale the locale (returned by getRuleSetDisplayNameLocales) for which the localized
702 * display name is desired
703 * @return the display name for the given index, which might be bogus if there is an error
704 * @see #getRuleSetName
705 * @stable ICU 3.2
706 */
707 virtual UnicodeString getRuleSetDisplayName(int32_t index,
708 const Locale& locale = Locale::getDefault());
709
710 /**
711 * Return the rule set display name for the provided rule set and locale.
712 * The locale is matched against the locales for which there is display name data, using
713 * normal fallback rules. If no locale matches, the default display name is returned.
714 * @return the display name for the rule set
715 * @stable ICU 3.2
716 * @see #getRuleSetDisplayName
717 */
718 virtual UnicodeString getRuleSetDisplayName(const UnicodeString& ruleSetName,
719 const Locale& locale = Locale::getDefault());
720
721 /**
722 * Formats the specified 32-bit number using the default ruleset.
723 * @param number The number to format.
724 * @param toAppendTo the string that will hold the (appended) result
725 * @param pos the fieldposition
726 * @return A textual representation of the number.
727 * @stable ICU 2.0
728 */
729 virtual UnicodeString& format(int32_t number,
730 UnicodeString& toAppendTo,
731 FieldPosition& pos) const;
732
733 /**
734 * Formats the specified 64-bit number using the default ruleset.
735 * @param number The number to format.
736 * @param toAppendTo the string that will hold the (appended) result
737 * @param pos the fieldposition
738 * @return A textual representation of the number.
739 * @stable ICU 2.1
740 */
741 virtual UnicodeString& format(int64_t number,
742 UnicodeString& toAppendTo,
743 FieldPosition& pos) const;
744 /**
745 * Formats the specified number using the default ruleset.
746 * @param number The number to format.
747 * @param toAppendTo the string that will hold the (appended) result
748 * @param pos the fieldposition
749 * @return A textual representation of the number.
750 * @stable ICU 2.0
751 */
752 virtual UnicodeString& format(double number,
753 UnicodeString& toAppendTo,
754 FieldPosition& pos) const;
755
756 /**
757 * Formats the specified number using the named ruleset.
758 * @param number The number to format.
759 * @param ruleSetName The name of the rule set to format the number with.
760 * This must be the name of a valid public rule set for this formatter.
761 * @param toAppendTo the string that will hold the (appended) result
762 * @param pos the fieldposition
763 * @param status the status
764 * @return A textual representation of the number.
765 * @stable ICU 2.0
766 */
767 virtual UnicodeString& format(int32_t number,
768 const UnicodeString& ruleSetName,
769 UnicodeString& toAppendTo,
770 FieldPosition& pos,
771 UErrorCode& status) const;
772 /**
773 * Formats the specified 64-bit number using the named ruleset.
774 * @param number The number to format.
775 * @param ruleSetName The name of the rule set to format the number with.
776 * This must be the name of a valid public rule set for this formatter.
777 * @param toAppendTo the string that will hold the (appended) result
778 * @param pos the fieldposition
779 * @param status the status
780 * @return A textual representation of the number.
781 * @stable ICU 2.1
782 */
783 virtual UnicodeString& format(int64_t number,
784 const UnicodeString& ruleSetName,
785 UnicodeString& toAppendTo,
786 FieldPosition& pos,
787 UErrorCode& status) const;
788 /**
789 * Formats the specified number using the named ruleset.
790 * @param number The number to format.
791 * @param ruleSetName The name of the rule set to format the number with.
792 * This must be the name of a valid public rule set for this formatter.
793 * @param toAppendTo the string that will hold the (appended) result
794 * @param pos the fieldposition
795 * @param status the status
796 * @return A textual representation of the number.
797 * @stable ICU 2.0
798 */
799 virtual UnicodeString& format(double number,
800 const UnicodeString& ruleSetName,
801 UnicodeString& toAppendTo,
802 FieldPosition& pos,
803 UErrorCode& status) const;
804
805 /**
806 * Formats the specified number using the default ruleset.
807 * @param obj The number to format.
808 * @param toAppendTo the string that will hold the (appended) result
809 * @param pos the fieldposition
810 * @param status the status
811 * @return A textual representation of the number.
812 * @stable ICU 2.0
813 */
814 virtual UnicodeString& format(const Formattable& obj,
815 UnicodeString& toAppendTo,
816 FieldPosition& pos,
817 UErrorCode& status) const;
818 /**
819 * Redeclared Format method.
820 * @param obj the object to be formatted.
821 * @param result Output param which will receive the formatted string.
822 * @param status Output param set to success/failure code
823 * @return A reference to 'result'.
824 * @stable ICU 2.0
825 */
826 UnicodeString& format(const Formattable& obj,
827 UnicodeString& result,
828 UErrorCode& status) const;
829
830 /**
831 * Redeclared NumberFormat method.
832 * @param number the double value to be formatted.
833 * @param output Output param which will receive the formatted string.
834 * @return A reference to 'output'.
835 * @stable ICU 2.0
836 */
837 UnicodeString& format(double number,
838 UnicodeString& output) const;
839
840 /**
841 * Redeclared NumberFormat method.
842 * @param number the long value to be formatted.
843 * @param output Output param which will receive the formatted string.
844 * @return A reference to 'output'.
845 * @stable ICU 2.0
846 */
847 UnicodeString& format(int32_t number,
848 UnicodeString& output) const;
849
850 /**
851 * Parses the specfied string, beginning at the specified position, according
852 * to this formatter's rules. This will match the string against all of the
853 * formatter's public rule sets and return the value corresponding to the longest
854 * parseable substring. This function's behavior is affected by the lenient
855 * parse mode.
856 * @param text The string to parse
857 * @param result the result of the parse, either a double or a long.
858 * @param parsePosition On entry, contains the position of the first character
859 * in "text" to examine. On exit, has been updated to contain the position
860 * of the first character in "text" that wasn't consumed by the parse.
861 * @see #setLenient
862 * @stable ICU 2.0
863 */
864 virtual void parse(const UnicodeString& text,
865 Formattable& result,
866 ParsePosition& parsePosition) const;
867
868
869 /**
870 * Redeclared Format method.
871 * @param text The string to parse
872 * @param result the result of the parse, either a double or a long.
873 * @param status Output param set to failure code when a problem occurs.
874 * @stable ICU 2.0
875 */
876 virtual inline void parse(const UnicodeString& text,
877 Formattable& result,
878 UErrorCode& status) const;
879
880 #if !UCONFIG_NO_COLLATION
881
882 /**
883 * Turns lenient parse mode on and off.
884 *
885 * When in lenient parse mode, the formatter uses a Collator for parsing the text.
886 * Only primary differences are treated as significant. This means that case
887 * differences, accent differences, alternate spellings of the same letter
888 * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in
889 * matching the text. In many cases, numerals will be accepted in place of words
890 * or phrases as well.
891 *
892 * For example, all of the following will correctly parse as 255 in English in
893 * lenient-parse mode:
894 * <br>"two hundred fifty-five"
895 * <br>"two hundred fifty five"
896 * <br>"TWO HUNDRED FIFTY-FIVE"
897 * <br>"twohundredfiftyfive"
898 * <br>"2 hundred fifty-5"
899 *
900 * The Collator used is determined by the locale that was
901 * passed to this object on construction. The description passed to this object
902 * on construction may supply additional collation rules that are appended to the
903 * end of the default collator for the locale, enabling additional equivalences
904 * (such as adding more ignorable characters or permitting spelled-out version of
905 * symbols; see the demo program for examples).
906 *
907 * It's important to emphasize that even strict parsing is relatively lenient: it
908 * will accept some text that it won't produce as output. In English, for example,
909 * it will correctly parse "two hundred zero" and "fifteen hundred".
910 *
911 * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
912 * @see RuleBasedCollator
913 * @stable ICU 2.0
914 */
915 virtual void setLenient(UBool enabled);
916
917 /**
918 * Returns true if lenient-parse mode is turned on. Lenient parsing is off
919 * by default.
920 * @return true if lenient-parse mode is turned on.
921 * @see #setLenient
922 * @stable ICU 2.0
923 */
924 virtual inline UBool isLenient(void) const;
925
926 #endif
927
928 /**
929 * Override the default rule set to use. If ruleSetName is null, reset
930 * to the initial default rule set. If the rule set is not a public rule set name,
931 * U_ILLEGAL_ARGUMENT_ERROR is returned in status.
932 * @param ruleSetName the name of the rule set, or null to reset the initial default.
933 * @param status set to failure code when a problem occurs.
934 * @stable ICU 2.6
935 */
936 virtual void setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status);
937
938 /**
939 * Return the name of the current default rule set. If the current rule set is
940 * not public, returns a bogus (and empty) UnicodeString.
941 * @return the name of the current default rule set
942 * @stable ICU 3.0
943 */
944 virtual UnicodeString getDefaultRuleSetName() const;
945
946 public:
947 /**
948 * ICU "poor man's RTTI", returns a UClassID for this class.
949 *
950 * @stable ICU 2.8
951 */
952 static UClassID U_EXPORT2 getStaticClassID(void);
953
954 /**
955 * ICU "poor man's RTTI", returns a UClassID for the actual class.
956 *
957 * @stable ICU 2.8
958 */
959 virtual UClassID getDynamicClassID(void) const;
960
961 private:
962 RuleBasedNumberFormat(); // default constructor not implemented
963
964 // this will ref the localizations if they are not NULL
965 // caller must deref to get adoption
966 RuleBasedNumberFormat(const UnicodeString& description, LocalizationInfo* localizations,
967 const Locale& locale, UParseError& perror, UErrorCode& status);
968
969 void init(const UnicodeString& rules, LocalizationInfo* localizations, UParseError& perror, UErrorCode& status);
970 void dispose();
971 void stripWhitespace(UnicodeString& src);
972 void initDefaultRuleSet();
973 void format(double number, NFRuleSet& ruleSet);
974 NFRuleSet* findRuleSet(const UnicodeString& name, UErrorCode& status) const;
975
976 /* friend access */
977 friend class NFSubstitution;
978 friend class NFRule;
979 friend class FractionalPartSubstitution;
980
981 inline NFRuleSet * getDefaultRuleSet() const;
982 Collator * getCollator() const;
983 DecimalFormatSymbols * getDecimalFormatSymbols() const;
984
985 private:
986 NFRuleSet **ruleSets;
987 NFRuleSet *defaultRuleSet;
988 Locale locale;
989 Collator* collator;
990 DecimalFormatSymbols* decimalFormatSymbols;
991 UBool lenient;
992 UnicodeString* lenientParseRules;
993 LocalizationInfo* localizations;
994 };
995
996 // ---------------
997
998 inline UnicodeString&
format(const Formattable & obj,UnicodeString & result,UErrorCode & status)999 RuleBasedNumberFormat::format(const Formattable& obj,
1000 UnicodeString& result,
1001 UErrorCode& status) const
1002 {
1003 // Don't use Format:: - use immediate base class only,
1004 // in case immediate base modifies behavior later.
1005 // dlf - the above comment is bogus, if there were a reason to modify
1006 // it, it would be virtual, and there's no reason because it is
1007 // a one-line macro in NumberFormat anyway, just like this one.
1008 return NumberFormat::format(obj, result, status);
1009 }
1010
1011 inline UnicodeString&
format(double number,UnicodeString & output)1012 RuleBasedNumberFormat::format(double number, UnicodeString& output) const {
1013 FieldPosition pos(0);
1014 return format(number, output, pos);
1015 }
1016
1017 inline UnicodeString&
format(int32_t number,UnicodeString & output)1018 RuleBasedNumberFormat::format(int32_t number, UnicodeString& output) const {
1019 FieldPosition pos(0);
1020 return format(number, output, pos);
1021 }
1022
1023 inline void
parse(const UnicodeString & text,Formattable & result,UErrorCode & status)1024 RuleBasedNumberFormat::parse(const UnicodeString& text, Formattable& result, UErrorCode& status) const
1025 {
1026 NumberFormat::parse(text, result, status);
1027 }
1028
1029 #if !UCONFIG_NO_COLLATION
1030
1031 inline UBool
isLenient(void)1032 RuleBasedNumberFormat::isLenient(void) const {
1033 return lenient;
1034 }
1035
1036 #endif
1037
1038 inline NFRuleSet*
getDefaultRuleSet()1039 RuleBasedNumberFormat::getDefaultRuleSet() const {
1040 return defaultRuleSet;
1041 }
1042
1043 U_NAMESPACE_END
1044
1045 /* U_HAVE_RBNF */
1046 #endif
1047
1048 /* RBNF_H */
1049 #endif
1050