1 // © 2017 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 4 #include "unicode/utypes.h" 5 6 #if !UCONFIG_NO_FORMATTING 7 #ifndef __NUMBERFORMATTER_H__ 8 #define __NUMBERFORMATTER_H__ 9 10 #include "unicode/appendable.h" 11 #include "unicode/dcfmtsym.h" 12 #include "unicode/currunit.h" 13 #include "unicode/fieldpos.h" 14 #include "unicode/fpositer.h" 15 #include "unicode/measunit.h" 16 #include "unicode/nounit.h" 17 #include "unicode/plurrule.h" 18 #include "unicode/ucurr.h" 19 #include "unicode/unum.h" 20 21 #ifndef U_HIDE_DRAFT_API 22 23 /** 24 * \file 25 * \brief C++ API: Library for localized number formatting introduced in ICU 60. 26 * 27 * This library was introduced in ICU 60 to simplify the process of formatting localized number strings. 28 * Basic usage examples: 29 * 30 * <pre> 31 * // Most basic usage: 32 * NumberFormatter::withLocale(...).format(123).toString(); // 1,234 in en-US 33 * 34 * // Custom notation, unit, and rounding strategy: 35 * NumberFormatter::with() 36 * .notation(Notation::compactShort()) 37 * .unit(CurrencyUnit("EUR", status)) 38 * .rounding(Rounder::maxDigits(2)) 39 * .locale(...) 40 * .format(1234) 41 * .toString(); // €1.2K in en-US 42 * 43 * // Create a formatter in a singleton for use later: 44 * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...) 45 * .unit(NoUnit::percent()) 46 * .rounding(Rounder::fixedFraction(3)); 47 * formatter.format(5.9831).toString(); // 5.983% in en-US 48 * 49 * // Create a "template" in a singleton but without setting a locale until the call site: 50 * static const UnlocalizedNumberFormatter template = NumberFormatter::with() 51 * .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) 52 * .adoptUnit(MeasureUnit::createMeter(status)) 53 * .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME); 54 * template.locale(...).format(1234).toString(); // +1,234 meters in en-US 55 * </pre> 56 * 57 * <p> 58 * This API offers more features than DecimalFormat and is geared toward new users of ICU. 59 * 60 * <p> 61 * NumberFormatter instances are immutable and thread safe. This means that invoking a configuration method has no 62 * effect on the receiving instance; you must store and use the new number formatter instance it returns instead. 63 * 64 * <pre> 65 * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific()); 66 * formatter.rounding(Rounder.maxFraction(2)); // does nothing! 67 * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0" 68 * </pre> 69 * 70 * <p> 71 * This API is based on the <em>fluent</em> design pattern popularized by libraries such as Google's Guava. For 72 * extensive details on the design of this API, read <a href="https://goo.gl/szi5VB">the design doc</a>. 73 * 74 * @author Shane Carr 75 */ 76 77 /** 78 * An enum declaring how to render units, including currencies. Example outputs when formatting 123 USD and 123 79 * meters in <em>en-CA</em>: 80 * 81 * <p> 82 * <ul> 83 * <li>NARROW*: "$123.00" and "123 m" 84 * <li>SHORT: "US$ 123.00" and "123 m" 85 * <li>FULL_NAME: "123.00 US dollars" and "123 meters" 86 * <li>ISO_CODE: "USD 123.00" and undefined behavior 87 * <li>HIDDEN: "123.00" and "123" 88 * </ul> 89 * 90 * <p> 91 * * The narrow format for currencies is not currently supported; this is a known issue that will be fixed in a 92 * future version. See #11666 for more information. 93 * 94 * <p> 95 * This enum is similar to {@link com.ibm.icu.text.MeasureFormat.FormatWidth}. 96 * 97 * @draft ICU 60 98 */ 99 typedef enum UNumberUnitWidth { 100 /** 101 * Print an abbreviated version of the unit name. Similar to SHORT, but always use the shortest available 102 * abbreviation or symbol. This option can be used when the context hints at the identity of the unit. For more 103 * information on the difference between NARROW and SHORT, see SHORT. 104 * 105 * <p> 106 * In CLDR, this option corresponds to the "Narrow" format for measure units and the "¤¤¤¤¤" placeholder for 107 * currencies. 108 * 109 * @draft ICU 60 110 */ 111 UNUM_UNIT_WIDTH_NARROW, 112 113 /** 114 * Print an abbreviated version of the unit name. Similar to NARROW, but use a slightly wider abbreviation or 115 * symbol when there may be ambiguity. This is the default behavior. 116 * 117 * <p> 118 * For example, in <em>es-US</em>, the SHORT form for Fahrenheit is "{0} °F", but the NARROW form is "{0}°", 119 * since Fahrenheit is the customary unit for temperature in that locale. 120 * 121 * <p> 122 * In CLDR, this option corresponds to the "Short" format for measure units and the "¤" placeholder for 123 * currencies. 124 * 125 * @draft ICU 60 126 */ 127 UNUM_UNIT_WIDTH_SHORT, 128 129 /** 130 * Print the full name of the unit, without any abbreviations. 131 * 132 * <p> 133 * In CLDR, this option corresponds to the default format for measure units and the "¤¤¤" placeholder for 134 * currencies. 135 * 136 * @draft ICU 60 137 */ 138 UNUM_UNIT_WIDTH_FULL_NAME, 139 140 /** 141 * Use the three-digit ISO XXX code in place of the symbol for displaying currencies. The behavior of this 142 * option is currently undefined for use with measure units. 143 * 144 * <p> 145 * In CLDR, this option corresponds to the "¤¤" placeholder for currencies. 146 * 147 * @draft ICU 60 148 */ 149 UNUM_UNIT_WIDTH_ISO_CODE, 150 151 /** 152 * Format the number according to the specified unit, but do not display the unit. For currencies, apply 153 * monetary symbols and formats as with SHORT, but omit the currency symbol. For measure units, the behavior is 154 * equivalent to not specifying the unit at all. 155 * 156 * @draft ICU 60 157 */ 158 UNUM_UNIT_WIDTH_HIDDEN, 159 160 /** 161 * One more than the highest UNumberUnitWidth value. 162 * 163 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420. 164 */ 165 UNUM_UNIT_WIDTH_COUNT 166 } UNumberUnitWidth; 167 168 /** 169 * An enum declaring how to denote positive and negative numbers. Example outputs when formatting 123 and -123 in 170 * <em>en-US</em>: 171 * 172 * <p> 173 * <ul> 174 * <li>AUTO: "123", "-123" 175 * <li>ALWAYS: "+123", "-123" 176 * <li>NEVER: "123", "123" 177 * <li>ACCOUNTING: "$123", "($123)" 178 * <li>ACCOUNTING_ALWAYS: "+$123", "($123)" 179 * </ul> 180 * 181 * <p> 182 * The exact format, including the position and the code point of the sign, differ by locale. 183 * 184 * @draft ICU 60 185 */ 186 typedef enum UNumberSignDisplay { 187 /** 188 * Show the minus sign on negative numbers, and do not show the sign on positive numbers. This is the default 189 * behavior. 190 * 191 * @draft ICU 60 192 */ 193 UNUM_SIGN_AUTO, 194 195 /** 196 * Show the minus sign on negative numbers and the plus sign on positive numbers. 197 * 198 * @draft ICU 60 199 */ 200 UNUM_SIGN_ALWAYS, 201 202 /** 203 * Do not show the sign on positive or negative numbers. 204 * 205 * @draft ICU 60 206 */ 207 UNUM_SIGN_NEVER, 208 209 /** 210 * Use the locale-dependent accounting format on negative numbers, and do not show the sign on positive numbers. 211 * 212 * <p> 213 * The accounting format is defined in CLDR and varies by locale; in many Western locales, the format is a pair 214 * of parentheses around the number. 215 * 216 * <p> 217 * Note: Since CLDR defines the accounting format in the monetary context only, this option falls back to the 218 * AUTO sign display strategy when formatting without a currency unit. This limitation may be lifted in the 219 * future. 220 * 221 * @draft ICU 60 222 */ 223 UNUM_SIGN_ACCOUNTING, 224 225 /** 226 * Use the locale-dependent accounting format on negative numbers, and show the plus sign on positive numbers. 227 * For more information on the accounting format, see the ACCOUNTING sign display strategy. 228 * 229 * @draft ICU 60 230 */ 231 UNUM_SIGN_ACCOUNTING_ALWAYS, 232 233 /** 234 * One more than the highest UNumberSignDisplay value. 235 * 236 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420. 237 */ 238 UNUM_SIGN_COUNT 239 } UNumberSignDisplay; 240 241 /** 242 * An enum declaring how to render the decimal separator. 243 * 244 * <p> 245 * <ul> 246 * <li>UNUM_DECIMAL_SEPARATOR_AUTO: "1", "1.1" 247 * <li>UNUM_DECIMAL_SEPARATOR_ALWAYS: "1.", "1.1" 248 * </ul> 249 */ 250 typedef enum UNumberDecimalSeparatorDisplay { 251 /** 252 * Show the decimal separator when there are one or more digits to display after the separator, and do not show 253 * it otherwise. This is the default behavior. 254 * 255 * @draft ICU 60 256 */ 257 UNUM_DECIMAL_SEPARATOR_AUTO, 258 259 /** 260 * Always show the decimal separator, even if there are no digits to display after the separator. 261 * 262 * @draft ICU 60 263 */ 264 UNUM_DECIMAL_SEPARATOR_ALWAYS, 265 266 /** 267 * One more than the highest UNumberDecimalSeparatorDisplay value. 268 * 269 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420. 270 */ 271 UNUM_DECIMAL_SEPARATOR_COUNT 272 } UNumberDecimalMarkDisplay; 273 274 U_NAMESPACE_BEGIN namespace number { // icu::number 275 276 // Forward declarations: 277 class UnlocalizedNumberFormatter; 278 class LocalizedNumberFormatter; 279 class FormattedNumber; 280 class Notation; 281 class ScientificNotation; 282 class Rounder; 283 class FractionRounder; 284 class CurrencyRounder; 285 class IncrementRounder; 286 class Grouper; 287 class IntegerWidth; 288 289 namespace impl { 290 291 // Forward declarations: 292 class Padder; 293 struct MacroProps; 294 struct MicroProps; 295 class DecimalQuantity; 296 struct NumberFormatterResults; 297 class NumberFormatterImpl; 298 struct ParsedPatternInfo; 299 class ScientificModifier; 300 class MultiplierProducer; 301 class MutablePatternModifier; 302 class LongNameHandler; 303 class ScientificHandler; 304 class CompactHandler; 305 class Modifier; 306 class NumberStringBuilder; 307 308 } // namespace impl 309 310 // Reserve extra names in case they are added as classes in the future: 311 typedef Notation CompactNotation; 312 typedef Notation SimpleNotation; 313 314 /** 315 * A class that defines the notation style to be used when formatting numbers in NumberFormatter. 316 * 317 * @draft ICU 60 318 */ 319 class U_I18N_API Notation : public UMemory { 320 public: 321 /** 322 * Print the number using scientific notation (also known as scientific form, standard index form, or standard form 323 * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the 324 * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more 325 * digits after the decimal separator, and the corresponding power of 10 displayed after the "E". 326 * 327 * <p> 328 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3: 329 * 330 * <pre> 331 * 8.765E4 332 * 8.765E3 333 * 8.765E2 334 * 8.765E1 335 * 8.765E0 336 * 8.765E-1 337 * 8.765E-2 338 * 8.765E-3 339 * 0E0 340 * </pre> 341 * 342 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. 343 * @draft ICU 60 344 */ 345 static ScientificNotation scientific(); 346 347 /** 348 * Print the number using engineering notation, a variant of scientific notation in which the exponent must be 349 * divisible by 3. 350 * 351 * <p> 352 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3: 353 * 354 * <pre> 355 * 87.65E3 356 * 8.765E3 357 * 876.5E0 358 * 87.65E0 359 * 8.765E0 360 * 876.5E-3 361 * 87.65E-3 362 * 8.765E-3 363 * 0E0 364 * </pre> 365 * 366 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. 367 * @draft ICU 60 368 */ 369 static ScientificNotation engineering(); 370 371 /** 372 * Print the number using short-form compact notation. 373 * 374 * <p> 375 * <em>Compact notation</em>, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with 376 * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to 377 * engineering notation in how it scales numbers. 378 * 379 * <p> 380 * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing 381 * screen real estate. 382 * 383 * <p> 384 * In short form, the powers of ten are abbreviated. In <em>en-US</em>, the abbreviations are "K" for thousands, "M" 385 * for millions, "B" for billions, and "T" for trillions. Example outputs in <em>en-US</em> when printing 8.765E7 386 * through 8.765E0: 387 * 388 * <pre> 389 * 88M 390 * 8.8M 391 * 876K 392 * 88K 393 * 8.8K 394 * 876 395 * 88 396 * 8.8 397 * </pre> 398 * 399 * <p> 400 * When compact notation is specified without an explicit rounding strategy, numbers are rounded off to the closest 401 * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal 402 * separator if there is only one digit before the decimal separator. The default compact notation rounding strategy 403 * is equivalent to: 404 * 405 * <pre> 406 * Rounder.integer().withMinDigits(2) 407 * </pre> 408 * 409 * @return A CompactNotation for passing to the NumberFormatter notation() setter. 410 * @draft ICU 60 411 */ 412 static CompactNotation compactShort(); 413 414 /** 415 * Print the number using long-form compact notation. For more information on compact notation, see 416 * {@link #compactShort}. 417 * 418 * <p> 419 * In long form, the powers of ten are spelled out fully. Example outputs in <em>en-US</em> when printing 8.765E7 420 * through 8.765E0: 421 * 422 * <pre> 423 * 88 million 424 * 8.8 million 425 * 876 thousand 426 * 88 thousand 427 * 8.8 thousand 428 * 876 429 * 88 430 * 8.8 431 * </pre> 432 * 433 * @return A CompactNotation for passing to the NumberFormatter notation() setter. 434 * @draft ICU 60 435 */ 436 static CompactNotation compactLong(); 437 438 /** 439 * Print the number using simple notation without any scaling by powers of ten. This is the default behavior. 440 * 441 * <p> 442 * Since this is the default behavior, this method needs to be called only when it is necessary to override a 443 * previous setting. 444 * 445 * <p> 446 * Example outputs in <em>en-US</em> when printing 8.765E7 through 8.765E0: 447 * 448 * <pre> 449 * 87,650,000 450 * 8,765,000 451 * 876,500 452 * 87,650 453 * 8,765 454 * 876.5 455 * 87.65 456 * 8.765 457 * </pre> 458 * 459 * @return A SimpleNotation for passing to the NumberFormatter notation() setter. 460 * @draft ICU 60 461 */ 462 static SimpleNotation simple(); 463 464 private: 465 enum NotationType { 466 NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR 467 } fType; 468 469 union NotationUnion { 470 // For NTN_SCIENTIFIC 471 struct ScientificSettings { 472 int8_t fEngineeringInterval; 473 bool fRequireMinInt; 474 int8_t fMinExponentDigits; 475 UNumberSignDisplay fExponentSignDisplay; 476 } scientific; 477 478 // For NTN_COMPACT 479 UNumberCompactStyle compactStyle; 480 481 // For NTN_ERROR 482 UErrorCode errorCode; 483 } fUnion; 484 485 typedef NotationUnion::ScientificSettings ScientificSettings; 486 Notation(const NotationType & type,const NotationUnion & union_)487 Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {} 488 Notation(UErrorCode errorCode)489 Notation(UErrorCode errorCode) : fType(NTN_ERROR) { 490 fUnion.errorCode = errorCode; 491 } 492 Notation()493 Notation() : fType(NTN_SIMPLE), fUnion() {} 494 copyErrorTo(UErrorCode & status)495 UBool copyErrorTo(UErrorCode &status) const { 496 if (fType == NTN_ERROR) { 497 status = fUnion.errorCode; 498 return TRUE; 499 } 500 return FALSE; 501 } 502 503 // To allow MacroProps to initialize empty instances: 504 friend struct impl::MacroProps; 505 friend class ScientificNotation; 506 507 // To allow implementation to access internal types: 508 friend class impl::NumberFormatterImpl; 509 friend class impl::ScientificModifier; 510 friend class impl::ScientificHandler; 511 }; 512 513 /** 514 * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter. 515 * 516 * <p> 517 * To create a ScientificNotation, use one of the factory methods in {@link Notation}. 518 * 519 * @draft ICU 60 520 */ 521 class U_I18N_API ScientificNotation : public Notation { 522 public: 523 /** 524 * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if 525 * necessary. Useful for fixed-width display. 526 * 527 * <p> 528 * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in <em>en-US</em> instead of 529 * the default "1.23E2". 530 * 531 * @param minExponentDigits 532 * The minimum number of digits to show in the exponent. 533 * @return A ScientificNotation, for chaining. 534 * @draft ICU 60 535 */ 536 ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const; 537 538 /** 539 * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO, 540 * showing the minus sign but not the plus sign. 541 * 542 * <p> 543 * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in <em>en-US</em> 544 * instead of the default "1.23E2". 545 * 546 * @param exponentSignDisplay 547 * The strategy for displaying the sign in the exponent. 548 * @return A ScientificNotation, for chaining. 549 * @draft ICU 60 550 */ 551 ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const; 552 553 private: 554 // Inherit constructor 555 using Notation::Notation; 556 557 friend class Notation; 558 }; 559 560 // Reserve extra names in case they are added as classes in the future: 561 typedef Rounder DigitRounder; 562 563 /** 564 * A class that defines the rounding strategy to be used when formatting numbers in NumberFormatter. 565 * 566 * <p> 567 * To create a Rounder, use one of the factory methods. 568 * 569 * @draft ICU 60 570 */ 571 class U_I18N_API Rounder : public UMemory { 572 573 public: 574 /** 575 * Show all available digits to full precision. 576 * 577 * <p> 578 * <strong>NOTE:</strong> When formatting a <em>double</em>, this method, along with {@link #minFraction} and 579 * {@link #minDigits}, will trigger complex algorithm similar to <em>Dragon4</em> to determine the low-order digits 580 * and the number of digits to display based on the value of the double. If the number of fraction places or 581 * significant digits can be bounded, consider using {@link #maxFraction} or {@link #maxDigits} instead to maximize 582 * performance. For more information, read the following blog post. 583 * 584 * <p> 585 * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/ 586 * 587 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 588 * @draft ICU 60 589 */ 590 static Rounder unlimited(); 591 592 /** 593 * Show numbers rounded if necessary to the nearest integer. 594 * 595 * @return A FractionRounder for chaining or passing to the NumberFormatter rounding() setter. 596 * @draft ICU 60 597 */ 598 static FractionRounder integer(); 599 600 /** 601 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 602 * Additionally, pad with zeros to ensure that this number of places are always shown. 603 * 604 * <p> 605 * Example output with minMaxFractionPlaces = 3: 606 * 607 * <p> 608 * 87,650.000<br> 609 * 8,765.000<br> 610 * 876.500<br> 611 * 87.650<br> 612 * 8.765<br> 613 * 0.876<br> 614 * 0.088<br> 615 * 0.009<br> 616 * 0.000 (zero) 617 * 618 * <p> 619 * This method is equivalent to {@link #minMaxFraction} with both arguments equal. 620 * 621 * @param minMaxFractionPlaces 622 * The minimum and maximum number of numerals to display after the decimal separator (rounding if too 623 * long or padding with zeros if too short). 624 * @return A FractionRounder for chaining or passing to the NumberFormatter rounding() setter. 625 * @draft ICU 60 626 */ 627 static FractionRounder fixedFraction(int32_t minMaxFractionPlaces); 628 629 /** 630 * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if 631 * necessary. Do not perform rounding (display numbers to their full precision). 632 * 633 * <p> 634 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}. 635 * 636 * @param minFractionPlaces 637 * The minimum number of numerals to display after the decimal separator (padding with zeros if 638 * necessary). 639 * @return A FractionRounder for chaining or passing to the NumberFormatter rounding() setter. 640 * @draft ICU 60 641 */ 642 static FractionRounder minFraction(int32_t minFractionPlaces); 643 644 /** 645 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 646 * Unlike the other fraction rounding strategies, this strategy does <em>not</em> pad zeros to the end of the 647 * number. 648 * 649 * @param maxFractionPlaces 650 * The maximum number of numerals to display after the decimal mark (rounding if necessary). 651 * @return A FractionRounder for chaining or passing to the NumberFormatter rounding() setter. 652 * @draft ICU 60 653 */ 654 static FractionRounder maxFraction(int32_t maxFractionPlaces); 655 656 /** 657 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator); 658 * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if 659 * necessary. 660 * 661 * @param minFractionPlaces 662 * The minimum number of numerals to display after the decimal separator (padding with zeros if 663 * necessary). 664 * @param maxFractionPlaces 665 * The maximum number of numerals to display after the decimal separator (rounding if necessary). 666 * @return A FractionRounder for chaining or passing to the NumberFormatter rounding() setter. 667 * @draft ICU 60 668 */ 669 static FractionRounder minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces); 670 671 /** 672 * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally, 673 * pad with zeros to ensure that this number of significant digits/figures are always shown. 674 * 675 * <p> 676 * This method is equivalent to {@link #minMaxDigits} with both arguments equal. 677 * 678 * @param minMaxSignificantDigits 679 * The minimum and maximum number of significant digits to display (rounding if too long or padding with 680 * zeros if too short). 681 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 682 * @draft ICU 60 683 */ 684 static DigitRounder fixedDigits(int32_t minMaxSignificantDigits); 685 686 /** 687 * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not 688 * perform rounding (display numbers to their full precision). 689 * 690 * <p> 691 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}. 692 * 693 * @param minSignificantDigits 694 * The minimum number of significant digits to display (padding with zeros if too short). 695 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 696 * @draft ICU 60 697 */ 698 static DigitRounder minDigits(int32_t minSignificantDigits); 699 700 /** 701 * Show numbers rounded if necessary to a certain number of significant digits/figures. 702 * 703 * @param maxSignificantDigits 704 * The maximum number of significant digits to display (rounding if too long). 705 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 706 * @draft ICU 60 707 */ 708 static DigitRounder maxDigits(int32_t maxSignificantDigits); 709 710 /** 711 * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at 712 * least a certain number of significant digits, padding with zeros if necessary. 713 * 714 * @param minSignificantDigits 715 * The minimum number of significant digits to display (padding with zeros if necessary). 716 * @param maxSignificantDigits 717 * The maximum number of significant digits to display (rounding if necessary). 718 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 719 * @draft ICU 60 720 */ 721 static DigitRounder minMaxDigits(int32_t minSignificantDigits, int32_t maxSignificantDigits); 722 723 /** 724 * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the 725 * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5. 726 * 727 * <p> 728 * In order to ensure that numbers are padded to the appropriate number of fraction places, call 729 * withMinFraction() on the return value of this method. 730 * For example, to round to the nearest 0.5 and always display 2 numerals after the 731 * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run: 732 * 733 * <pre> 734 * Rounder::increment(0.5).withMinFraction(2) 735 * </pre> 736 * 737 * @param roundingIncrement 738 * The increment to which to round numbers. 739 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 740 * @draft ICU 60 741 */ 742 static IncrementRounder increment(double roundingIncrement); 743 744 /** 745 * Show numbers rounded and padded according to the rules for the currency unit. The most common rounding settings 746 * for currencies include <code>Rounder.fixedFraction(2)</code>, <code>Rounder.integer()</code>, and 747 * <code>Rounder.increment(0.05)</code> for cash transactions ("nickel rounding"). 748 * 749 * <p> 750 * The exact rounding details will be resolved at runtime based on the currency unit specified in the 751 * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another 752 * currency, the withCurrency() method can be called on the return value of this method. 753 * 754 * @param currencyUsage 755 * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may 756 * be limited by the available denominations of cash or coins). 757 * @return A CurrencyRounder for chaining or passing to the NumberFormatter rounding() setter. 758 * @draft ICU 60 759 */ 760 static CurrencyRounder currency(UCurrencyUsage currencyUsage); 761 762 /** 763 * Sets the rounding mode to use when picking the direction to round (up or down). Common values 764 * include HALF_EVEN, HALF_UP, and FLOOR. The default is HALF_EVEN. 765 * 766 * @param roundingMode 767 * The RoundingMode to use. 768 * @return A Rounder for passing to the NumberFormatter rounding() setter. 769 * @draft ICU 60 770 */ 771 Rounder withMode(UNumberFormatRoundingMode roundingMode) const; 772 773 private: 774 enum RounderType { 775 RND_BOGUS, 776 RND_NONE, 777 RND_FRACTION, 778 RND_SIGNIFICANT, 779 RND_FRACTION_SIGNIFICANT, 780 RND_INCREMENT, 781 RND_CURRENCY, 782 RND_PASS_THROUGH, 783 RND_ERROR 784 } fType; 785 786 union RounderUnion { 787 struct FractionSignificantSettings { 788 // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT 789 int8_t fMinFrac; 790 int8_t fMaxFrac; 791 int8_t fMinSig; 792 int8_t fMaxSig; 793 } fracSig; 794 struct IncrementSettings { 795 double fIncrement; 796 int32_t fMinFrac; 797 } increment; // For RND_INCREMENT 798 UCurrencyUsage currencyUsage; // For RND_CURRENCY 799 UErrorCode errorCode; // For RND_ERROR 800 } fUnion; 801 802 typedef RounderUnion::FractionSignificantSettings FractionSignificantSettings; 803 typedef RounderUnion::IncrementSettings IncrementSettings; 804 805 UNumberFormatRoundingMode fRoundingMode; 806 Rounder(const RounderType & type,const RounderUnion & union_,UNumberFormatRoundingMode roundingMode)807 Rounder(const RounderType &type, const RounderUnion &union_, UNumberFormatRoundingMode roundingMode) 808 : fType(type), fUnion(union_), fRoundingMode(roundingMode) {} 809 Rounder(UErrorCode errorCode)810 Rounder(UErrorCode errorCode) : fType(RND_ERROR) { 811 fUnion.errorCode = errorCode; 812 } 813 Rounder()814 Rounder() : fType(RND_BOGUS) {} 815 isBogus()816 bool isBogus() const { 817 return fType == RND_BOGUS; 818 } 819 copyErrorTo(UErrorCode & status)820 UBool copyErrorTo(UErrorCode &status) const { 821 if (fType == RND_ERROR) { 822 status = fUnion.errorCode; 823 return TRUE; 824 } 825 return FALSE; 826 } 827 828 // On the parent type so that this method can be called internally on Rounder instances. 829 Rounder withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const; 830 831 /** NON-CONST: mutates the current instance. */ 832 void setLocaleData(const CurrencyUnit ¤cy, UErrorCode &status); 833 834 void apply(impl::DecimalQuantity &value, UErrorCode &status) const; 835 836 /** Version of {@link #apply} that obeys minInt constraints. Used for scientific notation compatibility mode. */ 837 void apply(impl::DecimalQuantity &value, int32_t minInt, UErrorCode status); 838 839 int32_t 840 chooseMultiplierAndApply(impl::DecimalQuantity &input, const impl::MultiplierProducer &producer, 841 UErrorCode &status); 842 843 static FractionRounder constructFraction(int32_t minFrac, int32_t maxFrac); 844 845 static Rounder constructSignificant(int32_t minSig, int32_t maxSig); 846 847 static Rounder 848 constructFractionSignificant(const FractionRounder &base, int32_t minSig, int32_t maxSig); 849 850 static IncrementRounder constructIncrement(double increment, int32_t minFrac); 851 852 static CurrencyRounder constructCurrency(UCurrencyUsage usage); 853 854 static Rounder constructPassThrough(); 855 856 // To allow MacroProps/MicroProps to initialize bogus instances: 857 friend struct impl::MacroProps; 858 friend struct impl::MicroProps; 859 860 // To allow NumberFormatterImpl to access isBogus() and other internal methods: 861 friend class impl::NumberFormatterImpl; 862 863 // To give access to apply() and chooseMultiplierAndApply(): 864 friend class impl::MutablePatternModifier; 865 friend class impl::LongNameHandler; 866 friend class impl::ScientificHandler; 867 friend class impl::CompactHandler; 868 869 // To allow child classes to call private methods: 870 friend class FractionRounder; 871 friend class CurrencyRounder; 872 friend class IncrementRounder; 873 }; 874 875 /** 876 * A class that defines a rounding strategy based on a number of fraction places and optionally significant digits to be 877 * used when formatting numbers in NumberFormatter. 878 * 879 * <p> 880 * To create a FractionRounder, use one of the factory methods on Rounder. 881 * 882 * @draft ICU 60 883 */ 884 class U_I18N_API FractionRounder : public Rounder { 885 public: 886 /** 887 * Ensure that no less than this number of significant digits are retained when rounding according to fraction 888 * rules. 889 * 890 * <p> 891 * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum figures set to 2, 3.141 892 * becomes "3.1" instead. 893 * 894 * <p> 895 * This setting does not affect the number of trailing zeros. For example, 3.01 would print as "3", not "3.0". 896 * 897 * @param minSignificantDigits 898 * The number of significant figures to guarantee. 899 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 900 * @draft ICU 60 901 */ 902 Rounder withMinDigits(int32_t minSignificantDigits) const; 903 904 /** 905 * Ensure that no more than this number of significant digits are retained when rounding according to fraction 906 * rules. 907 * 908 * <p> 909 * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum figures set to 2, 123.4 910 * becomes "120" instead. 911 * 912 * <p> 913 * This setting does not affect the number of trailing zeros. For example, with fixed fraction of 2, 123.4 would 914 * become "120.00". 915 * 916 * @param maxSignificantDigits 917 * Round the number to no more than this number of significant figures. 918 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 919 * @draft ICU 60 920 */ 921 Rounder withMaxDigits(int32_t maxSignificantDigits) const; 922 923 private: 924 // Inherit constructor 925 using Rounder::Rounder; 926 927 // To allow parent class to call this class's constructor: 928 friend class Rounder; 929 }; 930 931 /** 932 * A class that defines a rounding strategy parameterized by a currency to be used when formatting numbers in 933 * NumberFormatter. 934 * 935 * <p> 936 * To create a CurrencyRounder, use one of the factory methods on Rounder. 937 * 938 * @draft ICU 60 939 */ 940 class U_I18N_API CurrencyRounder : public Rounder { 941 public: 942 /** 943 * Associates a currency with this rounding strategy. 944 * 945 * <p> 946 * <strong>Calling this method is <em>not required</em></strong>, because the currency specified in unit() 947 * is automatically applied to currency rounding strategies. However, 948 * this method enables you to override that automatic association. 949 * 950 * <p> 951 * This method also enables numbers to be formatted using currency rounding rules without explicitly using a 952 * currency format. 953 * 954 * @param currency 955 * The currency to associate with this rounding strategy. 956 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 957 * @draft ICU 60 958 */ 959 Rounder withCurrency(const CurrencyUnit ¤cy) const; 960 961 private: 962 // Inherit constructor 963 using Rounder::Rounder; 964 965 // To allow parent class to call this class's constructor: 966 friend class Rounder; 967 }; 968 969 /** 970 * A class that defines a rounding strategy parameterized by a rounding increment to be used when formatting numbers in 971 * NumberFormatter. 972 * 973 * <p> 974 * To create an IncrementRounder, use one of the factory methods on Rounder. 975 * 976 * @draft ICU 60 977 */ 978 class U_I18N_API IncrementRounder : public Rounder { 979 public: 980 /** 981 * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if 982 * necessary. By default, no trailing zeros are added. 983 * 984 * <p> 985 * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00", 986 * "0.50", "1.00", and "1.50". 987 * 988 * <p> 989 * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment. 990 * 991 * @param minFrac The minimum number of digits after the decimal separator. 992 * @return A Rounder for chaining or passing to the NumberFormatter rounding() setter. 993 * @draft ICU 60 994 */ 995 Rounder withMinFraction(int32_t minFrac) const; 996 997 private: 998 // Inherit constructor 999 using Rounder::Rounder; 1000 1001 // To allow parent class to call this class's constructor: 1002 friend class Rounder; 1003 }; 1004 1005 /** 1006 * @internal This API is a technical preview. It is likely to change in an upcoming release. 1007 */ 1008 class U_I18N_API Grouper : public UMemory { 1009 public: 1010 /** 1011 * @internal This API is a technical preview. It is likely to change in an upcoming release. 1012 */ 1013 static Grouper defaults(); 1014 1015 /** 1016 * @internal This API is a technical preview. It is likely to change in an upcoming release. 1017 */ 1018 static Grouper minTwoDigits(); 1019 1020 /** 1021 * @internal This API is a technical preview. It is likely to change in an upcoming release. 1022 */ 1023 static Grouper none(); 1024 1025 private: 1026 int8_t fGrouping1; // -3 means "bogus"; -2 means "needs locale data"; -1 means "no grouping" 1027 int8_t fGrouping2; 1028 bool fMin2; 1029 Grouper(int8_t grouping1,int8_t grouping2,bool min2)1030 Grouper(int8_t grouping1, int8_t grouping2, bool min2) 1031 : fGrouping1(grouping1), fGrouping2(grouping2), fMin2(min2) {} 1032 Grouper()1033 Grouper() : fGrouping1(-3) {}; 1034 isBogus()1035 bool isBogus() const { 1036 return fGrouping1 == -3; 1037 } 1038 1039 /** NON-CONST: mutates the current instance. */ 1040 void setLocaleData(const impl::ParsedPatternInfo &patternInfo); 1041 1042 bool groupAtPosition(int32_t position, const impl::DecimalQuantity &value) const; 1043 1044 // To allow MacroProps/MicroProps to initialize empty instances: 1045 friend struct impl::MacroProps; 1046 friend struct impl::MicroProps; 1047 1048 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1049 friend class impl::NumberFormatterImpl; 1050 }; 1051 1052 /** 1053 * A class that defines the strategy for padding and truncating integers before the decimal separator. 1054 * 1055 * <p> 1056 * To create an IntegerWidth, use one of the factory methods. 1057 * 1058 * @draft ICU 60 1059 * @see NumberFormatter 1060 */ 1061 class U_I18N_API IntegerWidth : public UMemory { 1062 public: 1063 /** 1064 * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator. 1065 * 1066 * <p> 1067 * For example, with minInt=3, the number 55 will get printed as "055". 1068 * 1069 * @param minInt 1070 * The minimum number of places before the decimal separator. 1071 * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter. 1072 * @draft ICU 60 1073 * @see NumberFormatter 1074 */ 1075 static IntegerWidth zeroFillTo(int32_t minInt); 1076 1077 /** 1078 * Truncate numbers exceeding a certain number of numerals before the decimal separator. 1079 * 1080 * For example, with maxInt=3, the number 1234 will get printed as "234". 1081 * 1082 * @param maxInt 1083 * The maximum number of places before the decimal separator. 1084 * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter. 1085 * @draft ICU 60 1086 * @see NumberFormatter 1087 */ 1088 IntegerWidth truncateAt(int32_t maxInt); 1089 1090 private: 1091 union { 1092 struct { 1093 int8_t fMinInt; 1094 int8_t fMaxInt; 1095 } minMaxInt; 1096 UErrorCode errorCode; 1097 } fUnion; 1098 bool fHasError = false; 1099 1100 IntegerWidth(int8_t minInt, int8_t maxInt); 1101 IntegerWidth(UErrorCode errorCode)1102 IntegerWidth(UErrorCode errorCode) { // NOLINT 1103 fUnion.errorCode = errorCode; 1104 fHasError = true; 1105 } 1106 IntegerWidth()1107 IntegerWidth() { // NOLINT 1108 fUnion.minMaxInt.fMinInt = -1; 1109 } 1110 isBogus()1111 bool isBogus() const { 1112 return !fHasError && fUnion.minMaxInt.fMinInt == -1; 1113 } 1114 copyErrorTo(UErrorCode & status)1115 UBool copyErrorTo(UErrorCode &status) const { 1116 if (fHasError) { 1117 status = fUnion.errorCode; 1118 return TRUE; 1119 } 1120 return FALSE; 1121 } 1122 1123 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const; 1124 1125 // To allow MacroProps/MicroProps to initialize empty instances: 1126 friend struct impl::MacroProps; 1127 friend struct impl::MicroProps; 1128 1129 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1130 friend class impl::NumberFormatterImpl; 1131 }; 1132 1133 namespace impl { 1134 1135 /** 1136 * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built 1137 * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path. 1138 * 1139 * @internal 1140 */ 1141 static constexpr int32_t DEFAULT_THRESHOLD = 3; 1142 1143 /** @internal */ 1144 class U_I18N_API SymbolsWrapper : public UMemory { 1145 public: 1146 /** @internal */ SymbolsWrapper()1147 SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {} 1148 1149 /** @internal */ 1150 SymbolsWrapper(const SymbolsWrapper &other); 1151 1152 /** @internal */ 1153 ~SymbolsWrapper(); 1154 1155 /** @internal */ 1156 SymbolsWrapper &operator=(const SymbolsWrapper &other); 1157 1158 /** 1159 * The provided object is copied, but we do not adopt it. 1160 * @internal 1161 */ 1162 void setTo(const DecimalFormatSymbols &dfs); 1163 1164 /** 1165 * Adopt the provided object. 1166 * @internal 1167 */ 1168 void setTo(const NumberingSystem *ns); 1169 1170 /** 1171 * Whether the object is currently holding a DecimalFormatSymbols. 1172 * @internal 1173 */ 1174 bool isDecimalFormatSymbols() const; 1175 1176 /** 1177 * Whether the object is currently holding a NumberingSystem. 1178 * @internal 1179 */ 1180 bool isNumberingSystem() const; 1181 1182 /** 1183 * Get the DecimalFormatSymbols pointer. No ownership change. 1184 * @internal 1185 */ 1186 const DecimalFormatSymbols *getDecimalFormatSymbols() const; 1187 1188 /** 1189 * Get the NumberingSystem pointer. No ownership change. 1190 * @internal 1191 */ 1192 const NumberingSystem *getNumberingSystem() const; 1193 1194 /** @internal */ copyErrorTo(UErrorCode & status)1195 UBool copyErrorTo(UErrorCode &status) const { 1196 if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) { 1197 status = U_MEMORY_ALLOCATION_ERROR; 1198 return TRUE; 1199 } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) { 1200 status = U_MEMORY_ALLOCATION_ERROR; 1201 return TRUE; 1202 } 1203 return FALSE; 1204 } 1205 1206 private: 1207 enum SymbolsPointerType { 1208 SYMPTR_NONE, SYMPTR_DFS, SYMPTR_NS 1209 } fType; 1210 1211 union { 1212 const DecimalFormatSymbols *dfs; 1213 const NumberingSystem *ns; 1214 } fPtr; 1215 1216 void doCopyFrom(const SymbolsWrapper &other); 1217 1218 void doCleanup(); 1219 }; 1220 1221 /** @internal */ 1222 class U_I18N_API Padder : public UMemory { 1223 public: 1224 /** @internal */ 1225 static Padder none(); 1226 1227 /** @internal */ 1228 static Padder codePoints(UChar32 cp, int32_t targetWidth, UNumberFormatPadPosition position); 1229 1230 private: 1231 UChar32 fWidth; // -3 = error; -2 = bogus; -1 = no padding 1232 union { 1233 struct { 1234 int32_t fCp; 1235 UNumberFormatPadPosition fPosition; 1236 } padding; 1237 UErrorCode errorCode; 1238 } fUnion; 1239 1240 Padder(UChar32 cp, int32_t width, UNumberFormatPadPosition position); 1241 1242 Padder(int32_t width); 1243 Padder(UErrorCode errorCode)1244 Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT 1245 fUnion.errorCode = errorCode; 1246 } 1247 Padder()1248 Padder() : fWidth(-2) {} // NOLINT 1249 isBogus()1250 bool isBogus() const { 1251 return fWidth == -2; 1252 } 1253 copyErrorTo(UErrorCode & status)1254 UBool copyErrorTo(UErrorCode &status) const { 1255 if (fWidth == -3) { 1256 status = fUnion.errorCode; 1257 return TRUE; 1258 } 1259 return FALSE; 1260 } 1261 isValid()1262 bool isValid() const { 1263 return fWidth > 0; 1264 } 1265 1266 int32_t padAndApply(const impl::Modifier &mod1, const impl::Modifier &mod2, 1267 impl::NumberStringBuilder &string, int32_t leftIndex, int32_t rightIndex, 1268 UErrorCode &status) const; 1269 1270 // To allow MacroProps/MicroProps to initialize empty instances: 1271 friend struct MacroProps; 1272 friend struct MicroProps; 1273 1274 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1275 friend class impl::NumberFormatterImpl; 1276 }; 1277 1278 /** @internal */ 1279 struct U_I18N_API MacroProps : public UMemory { 1280 /** @internal */ 1281 Notation notation; 1282 1283 /** @internal */ 1284 MeasureUnit unit; // = NoUnit::base(); 1285 1286 /** @internal */ 1287 Rounder rounder; // = Rounder(); (bogus) 1288 1289 /** @internal */ 1290 Grouper grouper; // = Grouper(); (bogus) 1291 1292 /** @internal */ 1293 Padder padder; // = Padder(); (bogus) 1294 1295 /** @internal */ 1296 IntegerWidth integerWidth; // = IntegerWidth(); (bogus) 1297 1298 /** @internal */ 1299 SymbolsWrapper symbols; 1300 1301 // UNUM_XYZ_COUNT denotes null (bogus) values. 1302 1303 /** @internal */ 1304 UNumberUnitWidth unitWidth = UNUM_UNIT_WIDTH_COUNT; 1305 1306 /** @internal */ 1307 UNumberSignDisplay sign = UNUM_SIGN_COUNT; 1308 1309 /** @internal */ 1310 UNumberDecimalSeparatorDisplay decimal = UNUM_DECIMAL_SEPARATOR_COUNT; 1311 1312 /** @internal */ 1313 PluralRules *rules = nullptr; // no ownership 1314 1315 /** @internal */ 1316 int32_t threshold = DEFAULT_THRESHOLD; 1317 Locale locale; 1318 1319 /** 1320 * Check all members for errors. 1321 * @internal 1322 */ copyErrorToMacroProps1323 bool copyErrorTo(UErrorCode &status) const { 1324 return notation.copyErrorTo(status) || rounder.copyErrorTo(status) || 1325 padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) || 1326 symbols.copyErrorTo(status); 1327 } 1328 }; 1329 1330 } // namespace impl 1331 1332 /** 1333 * An abstract base class for specifying settings related to number formatting. This class is implemented by 1334 * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. 1335 */ 1336 template<typename Derived> 1337 class U_I18N_API NumberFormatterSettings { 1338 public: 1339 /** 1340 * Specifies the notation style (simple, scientific, or compact) for rendering numbers. 1341 * 1342 * <ul> 1343 * <li>Simple notation: "12,300" 1344 * <li>Scientific notation: "1.23E4" 1345 * <li>Compact notation: "12K" 1346 * </ul> 1347 * 1348 * <p> 1349 * All notation styles will be properly localized with locale data, and all notation styles are compatible with 1350 * units, rounding strategies, and other number formatter settings. 1351 * 1352 * <p> 1353 * Pass this method the return value of a {@link Notation} factory method. For example: 1354 * 1355 * <pre> 1356 * NumberFormatter::with().notation(Notation::compactShort()) 1357 * </pre> 1358 * 1359 * The default is to use simple notation. 1360 * 1361 * @param notation 1362 * The notation strategy to use. 1363 * @return The fluent chain. 1364 * @see Notation 1365 * @draft ICU 60 1366 */ 1367 Derived notation(const Notation ¬ation) const; 1368 1369 /** 1370 * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers. 1371 * 1372 * <ul> 1373 * <li>Unit of measure: "12.3 meters" 1374 * <li>Currency: "$12.30" 1375 * <li>Percent: "12.3%" 1376 * </ul> 1377 * 1378 * <p> 1379 * All units will be properly localized with locale data, and all units are compatible with notation styles, 1380 * rounding strategies, and other number formatter settings. 1381 * 1382 * <p> 1383 * Pass this method any instance of {@link MeasureUnit}. For units of measure: 1384 * 1385 * <pre> 1386 * NumberFormatter.with().adoptUnit(MeasureUnit::createMeter(status)) 1387 * </pre> 1388 * 1389 * Currency: 1390 * 1391 * <pre> 1392 * NumberFormatter.with()::unit(CurrencyUnit(u"USD", status)) 1393 * </pre> 1394 * 1395 * Percent: 1396 * 1397 * <pre> 1398 * NumberFormatter.with()::unit(NoUnit.percent()) 1399 * </pre> 1400 * 1401 * The default is to render without units (equivalent to NoUnit.base()). 1402 * 1403 * @param unit 1404 * The unit to render. 1405 * @return The fluent chain. 1406 * @see MeasureUnit 1407 * @see Currency 1408 * @see NoUnit 1409 * @draft ICU 60 1410 */ 1411 Derived unit(const icu::MeasureUnit &unit) const; 1412 1413 /** 1414 * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory 1415 * methods, which return pointers that need ownership. 1416 * 1417 * @param unit 1418 * The unit to render. 1419 * @return The fluent chain. 1420 * @see #unit 1421 * @see MeasureUnit 1422 * @draft ICU 60 1423 */ 1424 Derived adoptUnit(const icu::MeasureUnit *unit) const; 1425 1426 /** 1427 * Specifies the rounding strategy to use when formatting numbers. 1428 * 1429 * <ul> 1430 * <li>Round to 3 decimal places: "3.142" 1431 * <li>Round to 3 significant figures: "3.14" 1432 * <li>Round to the closest nickel: "3.15" 1433 * <li>Do not perform rounding: "3.1415926..." 1434 * </ul> 1435 * 1436 * <p> 1437 * Pass this method the return value of one of the factory methods on {@link Rounder}. For example: 1438 * 1439 * <pre> 1440 * NumberFormatter::with().rounding(Rounder::fixedFraction(2)) 1441 * </pre> 1442 * 1443 * <p> 1444 * In most cases, the default rounding strategy is to round to 6 fraction places; i.e., 1445 * <code>Rounder.maxFraction(6)</code>. The exceptions are if compact notation is being used, then the compact 1446 * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency, 1447 * then standard currency rounding is used, which varies from currency to currency (see {@link Rounder#currency} for 1448 * details). 1449 * 1450 * @param rounder 1451 * The rounding strategy to use. 1452 * @return The fluent chain. 1453 * @see Rounder 1454 * @provisional This API might change or be removed in a future release. 1455 * @draft ICU 60 1456 */ 1457 Derived rounding(const Rounder &rounder) const; 1458 1459 #ifndef U_HIDE_INTERNAL_API 1460 1461 /** 1462 * Specifies the grouping strategy to use when formatting numbers. 1463 * 1464 * <ul> 1465 * <li>Default grouping: "12,300" and "1,230" 1466 * <li>Grouping with at least 2 digits: "12,300" and "1230" 1467 * <li>No grouping: "12300" and "1230" 1468 * </ul> 1469 * 1470 * <p> 1471 * The exact grouping widths will be chosen based on the locale. 1472 * 1473 * <p> 1474 * Pass this method the return value of one of the factory methods on {@link Grouper}. For example: 1475 * 1476 * <pre> 1477 * NumberFormatter::with().grouping(Grouper::min2()) 1478 * </pre> 1479 * 1480 * The default is to perform grouping without concern for the minimum grouping digits. 1481 * 1482 * @param grouper 1483 * The grouping strategy to use. 1484 * @return The fluent chain. 1485 * @see Grouper 1486 * @see Notation 1487 * @internal 1488 * @internal ICU 60: This API is technical preview. 1489 */ 1490 Derived grouping(const Grouper &grouper) const; 1491 1492 #endif /* U_HIDE_INTERNAL_API */ 1493 1494 /** 1495 * Specifies the minimum and maximum number of digits to render before the decimal mark. 1496 * 1497 * <ul> 1498 * <li>Zero minimum integer digits: ".08" 1499 * <li>One minimum integer digit: "0.08" 1500 * <li>Two minimum integer digits: "00.08" 1501 * </ul> 1502 * 1503 * <p> 1504 * Pass this method the return value of {@link IntegerWidth#zeroFillTo(int)}. For example: 1505 * 1506 * <pre> 1507 * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2)) 1508 * </pre> 1509 * 1510 * The default is to have one minimum integer digit. 1511 * 1512 * @param style 1513 * The integer width to use. 1514 * @return The fluent chain. 1515 * @see IntegerWidth 1516 * @draft ICU 60 1517 */ 1518 Derived integerWidth(const IntegerWidth &style) const; 1519 1520 /** 1521 * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering 1522 * numbers. 1523 * 1524 * <ul> 1525 * <li><em>en_US</em> symbols: "12,345.67" 1526 * <li><em>fr_FR</em> symbols: "12 345,67" 1527 * <li><em>de_CH</em> symbols: "12’345.67" 1528 * <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇" 1529 * </ul> 1530 * 1531 * <p> 1532 * Pass this method an instance of {@link DecimalFormatSymbols}. For example: 1533 * 1534 * <pre> 1535 * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status)) 1536 * </pre> 1537 * 1538 * <p> 1539 * <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale. 1540 * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar 1541 * numbering system. 1542 * 1543 * <p> 1544 * <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object 1545 * after passing it into the fluent chain will not be seen. 1546 * 1547 * <p> 1548 * <strong>Note:</strong> Calling this method will override the NumberingSystem previously specified in 1549 * {@link #symbols(NumberingSystem)}. 1550 * 1551 * <p> 1552 * The default is to choose the symbols based on the locale specified in the fluent chain. 1553 * 1554 * @param symbols 1555 * The DecimalFormatSymbols to use. 1556 * @return The fluent chain. 1557 * @see DecimalFormatSymbols 1558 * @draft ICU 60 1559 */ 1560 Derived symbols(const DecimalFormatSymbols &symbols) const; 1561 1562 /** 1563 * Specifies that the given numbering system should be used when fetching symbols. 1564 * 1565 * <ul> 1566 * <li>Latin numbering system: "12,345" 1567 * <li>Myanmar numbering system: "၁၂,၃၄၅" 1568 * <li>Math Sans Bold numbering system: "," 1569 * </ul> 1570 * 1571 * <p> 1572 * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin 1573 * alphabet numbering system (ASCII digits): 1574 * 1575 * <pre> 1576 * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status)) 1577 * </pre> 1578 * 1579 * <p> 1580 * <strong>Note:</strong> Calling this method will override the DecimalFormatSymbols previously specified in 1581 * {@link #symbols(DecimalFormatSymbols)}. 1582 * 1583 * <p> 1584 * The default is to choose the best numbering system for the locale. 1585 * 1586 * <p> 1587 * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods. 1588 * 1589 * @param symbols 1590 * The NumberingSystem to use. 1591 * @return The fluent chain. 1592 * @see NumberingSystem 1593 * @draft ICU 60 1594 */ 1595 Derived adoptSymbols(const NumberingSystem *symbols) const; 1596 1597 /** 1598 * Sets the width of the unit (measure unit or currency). Most common values: 1599 * 1600 * <ul> 1601 * <li>Short: "$12.00", "12 m" 1602 * <li>ISO Code: "USD 12.00" 1603 * <li>Full name: "12.00 US dollars", "12 meters" 1604 * </ul> 1605 * 1606 * <p> 1607 * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example: 1608 * 1609 * <pre> 1610 * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME) 1611 * </pre> 1612 * 1613 * <p> 1614 * The default is the SHORT width. 1615 * 1616 * @param width 1617 * The width to use when rendering numbers. 1618 * @return The fluent chain 1619 * @see UNumberUnitWidth 1620 * @draft ICU 60 1621 */ 1622 Derived unitWidth(const UNumberUnitWidth &width) const; 1623 1624 /** 1625 * Sets the plus/minus sign display strategy. Most common values: 1626 * 1627 * <ul> 1628 * <li>Auto: "123", "-123" 1629 * <li>Always: "+123", "-123" 1630 * <li>Accounting: "$123", "($123)" 1631 * </ul> 1632 * 1633 * <p> 1634 * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example: 1635 * 1636 * <pre> 1637 * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) 1638 * </pre> 1639 * 1640 * <p> 1641 * The default is AUTO sign display. 1642 * 1643 * @param width 1644 * The sign display strategy to use when rendering numbers. 1645 * @return The fluent chain 1646 * @see UNumberSignDisplay 1647 * @provisional This API might change or be removed in a future release. 1648 * @draft ICU 60 1649 */ 1650 Derived sign(const UNumberSignDisplay &width) const; 1651 1652 /** 1653 * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common 1654 * values: 1655 * 1656 * <ul> 1657 * <li>Auto: "1" 1658 * <li>Always: "1." 1659 * </ul> 1660 * 1661 * <p> 1662 * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example: 1663 * 1664 * <pre> 1665 * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS) 1666 * </pre> 1667 * 1668 * <p> 1669 * The default is AUTO decimal separator display. 1670 * 1671 * @param width 1672 * The decimal separator display strategy to use when rendering numbers. 1673 * @return The fluent chain 1674 * @see UNumberDecimalSeparatorDisplay 1675 * @provisional This API might change or be removed in a future release. 1676 * @draft ICU 60 1677 */ 1678 Derived decimal(const UNumberDecimalSeparatorDisplay &width) const; 1679 1680 #ifndef U_HIDE_INTERNAL_API 1681 1682 /** 1683 * Set the padding strategy. May be added to ICU 61; see #13338. 1684 * 1685 * @internal ICU 60: This API is ICU internal only. 1686 */ 1687 Derived padding(const impl::Padder &padder) const; 1688 1689 /** 1690 * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to 1691 * be built right away. A threshold of 0 prevents the data structures from being built. 1692 * 1693 * @internal ICU 60: This API is ICU internal only. 1694 */ 1695 Derived threshold(int32_t threshold) const; 1696 1697 #endif /* U_HIDE_INTERNAL_API */ 1698 1699 /** 1700 * Sets the UErrorCode if an error occurred in the fluent chain. 1701 * Preserves older error codes in the outErrorCode. 1702 * @return TRUE if U_FAILURE(outErrorCode) 1703 * @draft ICU 60 1704 */ copyErrorTo(UErrorCode & outErrorCode)1705 UBool copyErrorTo(UErrorCode &outErrorCode) const { 1706 if (U_FAILURE(outErrorCode)) { 1707 // Do not overwrite the older error code 1708 return TRUE; 1709 } 1710 fMacros.copyErrorTo(outErrorCode); 1711 return U_FAILURE(outErrorCode); 1712 } 1713 1714 protected: 1715 impl::MacroProps fMacros; 1716 1717 private: 1718 // Don't construct me directly! Use (Un)LocalizedNumberFormatter. 1719 NumberFormatterSettings() = default; 1720 1721 friend class LocalizedNumberFormatter; 1722 friend class UnlocalizedNumberFormatter; 1723 }; 1724 1725 /** 1726 * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified. 1727 * 1728 * @see NumberFormatter 1729 * @draft ICU 60 1730 */ 1731 class U_I18N_API UnlocalizedNumberFormatter 1732 : public NumberFormatterSettings<UnlocalizedNumberFormatter>, public UMemory { 1733 1734 public: 1735 /** 1736 * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols, 1737 * formats, and other data for number display. 1738 * 1739 * <p> 1740 * To use the Java default locale, call Locale::getDefault(): 1741 * 1742 * <pre> 1743 * NumberFormatter::with(). ... .locale(Locale::getDefault()) 1744 * </pre> 1745 * 1746 * @param locale 1747 * The locale to use when loading data for number formatting. 1748 * @return The fluent chain. 1749 * @draft ICU 60 1750 */ 1751 LocalizedNumberFormatter locale(const icu::Locale &locale) const; 1752 1753 // Make default copy constructor call the NumberFormatterSettings copy constructor. 1754 /** 1755 * Returns a copy of this UnlocalizedNumberFormatter. 1756 * @draft ICU 60 1757 */ UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter & other)1758 UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other) : UnlocalizedNumberFormatter( 1759 static_cast<const NumberFormatterSettings<UnlocalizedNumberFormatter> &>(other)) {} 1760 1761 private: 1762 UnlocalizedNumberFormatter() = default; 1763 1764 explicit UnlocalizedNumberFormatter( 1765 const NumberFormatterSettings<UnlocalizedNumberFormatter> &other); 1766 1767 // To give the fluent setters access to this class's constructor: 1768 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>; 1769 1770 // To give NumberFormatter::with() access to this class's constructor: 1771 friend class NumberFormatter; 1772 }; 1773 1774 /** 1775 * A NumberFormatter that has a locale associated with it; this means .format() methods are available. 1776 * 1777 * @see NumberFormatter 1778 * @draft ICU 60 1779 */ 1780 class U_I18N_API LocalizedNumberFormatter 1781 : public NumberFormatterSettings<LocalizedNumberFormatter>, public UMemory { 1782 public: 1783 /** 1784 * Format the given integer number to a string using the settings specified in the NumberFormatter fluent 1785 * setting chain. 1786 * 1787 * @param value 1788 * The number to format. 1789 * @param status 1790 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 1791 * @return A FormattedNumber object; call .toString() to get the string. 1792 * @draft ICU 60 1793 */ 1794 FormattedNumber formatInt(int64_t value, UErrorCode &status) const; 1795 1796 /** 1797 * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting 1798 * chain. 1799 * 1800 * @param value 1801 * The number to format. 1802 * @param status 1803 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 1804 * @return A FormattedNumber object; call .toString() to get the string. 1805 * @draft ICU 60 1806 */ 1807 FormattedNumber formatDouble(double value, UErrorCode &status) const; 1808 1809 /** 1810 * Format the given decimal number to a string using the settings 1811 * specified in the NumberFormatter fluent setting chain. 1812 * The syntax of the unformatted number is a "numeric string" 1813 * as defined in the Decimal Arithmetic Specification, available at 1814 * http://speleotrove.com/decimal 1815 * 1816 * @param value 1817 * The number to format. 1818 * @param status 1819 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 1820 * @return A FormattedNumber object; call .toString() to get the string. 1821 * @draft ICU 60 1822 */ 1823 FormattedNumber formatDecimal(StringPiece value, UErrorCode &status) const; 1824 1825 // Make default copy constructor call the NumberFormatterSettings copy constructor. 1826 /** 1827 * Returns a copy of this LocalizedNumberFormatter. 1828 * @draft ICU 60 1829 */ LocalizedNumberFormatter(const LocalizedNumberFormatter & other)1830 LocalizedNumberFormatter(const LocalizedNumberFormatter &other) : LocalizedNumberFormatter( 1831 static_cast<const NumberFormatterSettings<LocalizedNumberFormatter> &>(other)) {} 1832 1833 /** 1834 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own. 1835 * @draft ICU 60 1836 */ 1837 ~LocalizedNumberFormatter(); 1838 1839 private: 1840 const impl::NumberFormatterImpl* fCompiled {nullptr}; 1841 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t 1842 1843 LocalizedNumberFormatter() = default; 1844 1845 explicit LocalizedNumberFormatter(const NumberFormatterSettings<LocalizedNumberFormatter> &other); 1846 1847 LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale); 1848 1849 /** 1850 * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path 1851 * for the first few calls, and compiling a more efficient data structure if called repeatedly. 1852 * 1853 * <p> 1854 * This function is very hot, being called in every call to the number formatting pipeline. 1855 * 1856 * @param results 1857 * The results object. This method takes ownership. 1858 * @return The formatted number result. 1859 */ 1860 FormattedNumber formatImpl(impl::NumberFormatterResults *results, UErrorCode &status) const; 1861 1862 // To give the fluent setters access to this class's constructor: 1863 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>; 1864 friend class NumberFormatterSettings<LocalizedNumberFormatter>; 1865 1866 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor: 1867 friend class UnlocalizedNumberFormatter; 1868 }; 1869 1870 /** 1871 * The result of a number formatting operation. This class allows the result to be exported in several data types, 1872 * including a UnicodeString and a FieldPositionIterator. 1873 * 1874 * @draft ICU 60 1875 */ 1876 class U_I18N_API FormattedNumber : public UMemory { 1877 public: 1878 /** 1879 * Returns a UnicodeString representation of the formatted number. 1880 * 1881 * @return a UnicodeString containing the localized number. 1882 * @draft ICU 60 1883 */ 1884 UnicodeString toString() const; 1885 1886 /** 1887 * Appends the formatted number to an Appendable. 1888 * 1889 * @param appendable 1890 * The Appendable to which to append the formatted number string. 1891 * @return The same Appendable, for chaining. 1892 * @draft ICU 60 1893 * @see Appendable 1894 */ 1895 Appendable &appendTo(Appendable &appendable); 1896 1897 /** 1898 * Determine the start and end indices of the first occurrence of the given <em>field</em> in the output string. 1899 * This allows you to determine the locations of the integer part, fraction part, and sign. 1900 * 1901 * <p> 1902 * If multiple different field attributes are needed, this method can be called repeatedly, or if <em>all</em> field 1903 * attributes are needed, consider using populateFieldPositionIterator(). 1904 * 1905 * <p> 1906 * If a field occurs multiple times in an output string, such as a grouping separator, this method will only ever 1907 * return the first occurrence. Use populateFieldPositionIterator() to access all occurrences of an attribute. 1908 * 1909 * @param fieldPosition 1910 * The FieldPosition to populate with the start and end indices of the desired field. 1911 * @param status 1912 * Set if an error occurs while populating the FieldPosition. 1913 * @draft ICU 60 1914 * @see UNumberFormatFields 1915 */ 1916 void populateFieldPosition(FieldPosition &fieldPosition, UErrorCode &status); 1917 1918 /** 1919 * Export the formatted number to a FieldPositionIterator. This allows you to determine which characters in 1920 * the output string correspond to which <em>fields</em>, such as the integer part, fraction part, and sign. 1921 * 1922 * <p> 1923 * If information on only one field is needed, consider using populateFieldPosition() instead. 1924 * 1925 * @param iterator 1926 * The FieldPositionIterator to populate with all of the fields present in the formatted number. 1927 * @param status 1928 * Set if an error occurs while populating the FieldPositionIterator. 1929 * @draft ICU 60 1930 * @see UNumberFormatFields 1931 */ 1932 void populateFieldPositionIterator(FieldPositionIterator &iterator, UErrorCode &status); 1933 1934 /** 1935 * Destruct an instance of FormattedNumber, cleaning up any memory it might own. 1936 * @draft ICU 60 1937 */ 1938 ~FormattedNumber(); 1939 1940 private: 1941 // Can't use LocalPointer because NumberFormatterResults is forward-declared 1942 const impl::NumberFormatterResults *fResults; 1943 1944 // Error code for the terminal methods 1945 UErrorCode fErrorCode; 1946 FormattedNumber(impl::NumberFormatterResults * results)1947 explicit FormattedNumber(impl::NumberFormatterResults *results) 1948 : fResults(results), fErrorCode(U_ZERO_ERROR) {}; 1949 FormattedNumber(UErrorCode errorCode)1950 explicit FormattedNumber(UErrorCode errorCode) 1951 : fResults(nullptr), fErrorCode(errorCode) {}; 1952 1953 // To give LocalizedNumberFormatter format methods access to this class's constructor: 1954 friend class LocalizedNumberFormatter; 1955 }; 1956 1957 /** 1958 * See the main description in numberformatter.h for documentation and examples. 1959 * 1960 * @draft ICU 60 1961 */ 1962 class U_I18N_API NumberFormatter final { 1963 public: 1964 /** 1965 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at 1966 * the call site. 1967 * 1968 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining. 1969 * @draft ICU 60 1970 */ 1971 static UnlocalizedNumberFormatter with(); 1972 1973 /** 1974 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call 1975 * site. 1976 * 1977 * @param locale 1978 * The locale from which to load formats and symbols for number formatting. 1979 * @return A {@link LocalizedNumberFormatter}, to be used for chaining. 1980 * @draft ICU 60 1981 */ 1982 static LocalizedNumberFormatter withLocale(const Locale &locale); 1983 1984 /** 1985 * Use factory methods instead of the constructor to create a NumberFormatter. 1986 * @draft ICU 60 1987 */ 1988 NumberFormatter() = delete; 1989 }; 1990 1991 } // namespace number 1992 U_NAMESPACE_END 1993 1994 #endif // U_HIDE_DRAFT_API 1995 1996 #endif // __NUMBERFORMATTER_H__ 1997 1998 #endif /* #if !UCONFIG_NO_FORMATTING */ 1999