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