38 * // Most basic usage: 39 * NumberFormatter::withLocale(...).format(123).toString(); // 1,234 in en-US 40 * 41 * // Custom notation, unit, and rounding precision: 42 * NumberFormatter::with() 43 * .notation(Notation::compactShort()) 44 * .unit(CurrencyUnit("EUR", status)) 45 * .precision(Precision::maxDigits(2)) 46 * .locale(...) 47 * .format(1234) 48 * .toString(); // €1.2K in en-US 49 * 50 * // Create a formatter in a singleton by value for use later: 51 * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...) 52 * .unit(NoUnit::percent()) 53 * .precision(Precision::fixedFraction(3)); 54 * formatter.format(5.9831).toString(); // 5.983% in en-US 55 * 56 * // Create a "template" in a singleton unique_ptr but without setting a locale until the call site: 57 * std::unique_ptr template = NumberFormatter::with() 58 * .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) 59 * .unit(MeasureUnit::getMeter()) 60 * .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME) 61 * .clone(); 62 * template->locale(...).format(1234).toString(); // +1,234 meters in en-US 63 *
66 * This API offers more features than DecimalFormat and is geared toward new users of ICU. 67 * 68 *
69 * NumberFormatter instances (i.e., LocalizedNumberFormatter and UnlocalizedNumberFormatter) 70 * are immutable and thread safe. This means that invoking a configuration method has no 71 * effect on the receiving instance; you must store and use the new number formatter instance it returns instead. 72 * 73 *
74 * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific()); 75 * formatter.precision(Precision.maxFraction(2)); // does nothing! 76 * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0" 77 *
80 * This API is based on the fluent design pattern popularized by libraries such as Google's Guava. For 81 * extensive details on the design of this API, read the design doc. 82 * 83 *
84 * Note: To format monetary/currency values, specify the currency in the `.unit()` function. 85 * 86 * @author Shane Carr 87 */ 88 89 U_NAMESPACE_BEGIN 90 91 // Forward declarations: 92 class IFixedDecimal; 93 class FieldPositionIteratorHandler; 94 class FormattedStringBuilder; 95 96 namespace numparse { 97 namespace impl { 98 99 // Forward declarations: 100 class NumberParserImpl; 101 class MultiplierParseHandler; 102 103 } 104 } 105 106 namespace units { 107 108 // Forward declarations: 109 class UnitsRouter; 110 111 } // namespace units 112 113 namespace number { // icu::number 114 115 // Forward declarations: 116 class UnlocalizedNumberFormatter; 117 class LocalizedNumberFormatter; 118 class SimpleNumberFormatter; 119 class FormattedNumber; 120 class Notation; 121 class ScientificNotation; 122 class Precision; 123 class FractionPrecision; 124 class CurrencyPrecision; 125 class IncrementPrecision; 126 class IntegerWidth; 127 128 namespace impl { 129 130 // can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes 131 /** 132 * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig. 133 * 134 * @internal 135 */ 136 typedef int16_t digits_t; 137 138 // can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization 139 /** 140 * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built 141 * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path. 142 * 143 * @internal 144 */ 145 static constexpr int32_t kInternalDefaultThreshold = 3; 146 147 // Forward declarations: 148 class Padder; 149 struct MacroProps; 150 struct MicroProps; 151 class DecimalQuantity; 152 class UFormattedNumberData; 153 class NumberFormatterImpl; 154 struct ParsedPatternInfo; 155 class ScientificModifier; 156 class MultiplierProducer; 157 class RoundingImpl; 158 class ScientificHandler; 159 class Modifier; 160 class AffixPatternProvider; 161 class NumberPropertyMapper; 162 struct DecimalFormatProperties; 163 class MultiplierFormatHandler; 164 class CurrencySymbols; 165 class GeneratorHelpers; 166 class DecNum; 167 class NumberRangeFormatterImpl; 168 struct RangeMacroProps; 169 struct UFormattedNumberImpl; 170 class MutablePatternModifier; 171 class ImmutablePatternModifier; 172 struct DecimalFormatWarehouse; 173 struct SimpleMicroProps; 174 class AdoptingSignumModifierStore; 175 176 /** 177 * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp. 178 * Declared here so it can be friended. 179 * 180 * @internal 181 */ 182 void touchRangeLocales(impl::RangeMacroProps& macros); 183 184 } // namespace impl 185 186 /** 187 * Extra name reserved in case it is needed in the future. 188 * 189 * @stable ICU 63 190 */ 191 typedef Notation CompactNotation; 192 193 /** 194 * Extra name reserved in case it is needed in the future. 195 * 196 * @stable ICU 63 197 */ 198 typedef Notation SimpleNotation; 199 200 /** 201 * A class that defines the notation style to be used when formatting numbers in NumberFormatter. 202 * 203 * @stable ICU 60 204 */ 205 class U_I18N_API Notation : public UMemory { 206 public: 207 /** 208 * Print the number using scientific notation (also known as scientific form, standard index form, or standard form 209 * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the 210 * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more 211 * digits after the decimal separator, and the corresponding power of 10 displayed after the "E". 212 * 213 *
214 * Example outputs in en-US when printing 8.765E4 through 8.765E-3: 215 * 216 *
217 * 8.765E4 218 * 8.765E3 219 * 8.765E2 220 * 8.765E1 221 * 8.765E0 222 * 8.765E-1 223 * 8.765E-2 224 * 8.765E-3 225 * 0E0 226 *
238 * Example outputs in en-US when printing 8.765E4 through 8.765E-3: 239 * 240 *
241 * 87.65E3 242 * 8.765E3 243 * 876.5E0 244 * 87.65E0 245 * 8.765E0 246 * 876.5E-3 247 * 87.65E-3 248 * 8.765E-3 249 * 0E0 250 *
261 * Compact notation, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with 262 * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to 263 * engineering notation in how it scales numbers. 264 * 265 *
266 * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing 267 * screen real estate. 268 * 269 *
270 * In short form, the powers of ten are abbreviated. In en-US, the abbreviations are "K" for thousands, "M" 271 * for millions, "B" for billions, and "T" for trillions. Example outputs in en-US when printing 8.765E7 272 * through 8.765E0: 273 * 274 *
275 * 88M 276 * 8.8M 277 * 876K 278 * 88K 279 * 8.8K 280 * 876 281 * 88 282 * 8.8 283 *
286 * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest 287 * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal 288 * separator if there is only one digit before the decimal separator. The default compact notation rounding precision 289 * is equivalent to: 290 * 291 *
292 * Precision::integer().withMinDigits(2) 293 *
305 * In long form, the powers of ten are spelled out fully. Example outputs in en-US when printing 8.765E7 306 * through 8.765E0: 307 * 308 *
309 * 88 million 310 * 8.8 million 311 * 876 thousand 312 * 88 thousand 313 * 8.8 thousand 314 * 876 315 * 88 316 * 8.8 317 *
328 * Since this is the default behavior, this method needs to be called only when it is necessary to override a 329 * previous setting. 330 * 331 *
332 * Example outputs in en-US when printing 8.765E7 through 8.765E0: 333 * 334 *
335 * 87,650,000 336 * 8,765,000 337 * 876,500 338 * 87,650 339 * 8,765 340 * 876.5 341 * 87.65 342 * 8.765 343 *
411 * To create a ScientificNotation, use one of the factory methods in {@link Notation}. 412 * 413 * @stable ICU 60 414 */ 415 class U_I18N_API ScientificNotation : public Notation { 416 public: 417 /** 418 * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if 419 * necessary. Useful for fixed-width display. 420 * 421 *
422 * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in en-US instead of 423 * the default "1.23E2". 424 * 425 * @param minExponentDigits 426 * The minimum number of digits to show in the exponent. 427 * @return A ScientificNotation, for chaining. 428 * @stable ICU 60 429 */ 430 ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const; 431 432 /** 433 * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO, 434 * showing the minus sign but not the plus sign. 435 * 436 *
437 * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in en-US 438 * instead of the default "1.23E2". 439 * 440 * @param exponentSignDisplay 441 * The strategy for displaying the sign in the exponent. 442 * @return A ScientificNotation, for chaining. 443 * @stable ICU 60 444 */ 445 ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const; 446 447 private: 448 // Inherit constructor 449 using Notation::Notation; 450 451 // Raw constructor for NumberPropertyMapper 452 ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits, 453 UNumberSignDisplay fExponentSignDisplay); 454 455 friend class Notation; 456 457 // So that NumberPropertyMapper can create instances 458 friend class impl::NumberPropertyMapper; 459 }; 460 461 /** 462 * Extra name reserved in case it is needed in the future. 463 * 464 * @stable ICU 63 465 */ 466 typedef Precision SignificantDigitsPrecision; 467 468 /** 469 * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter. 470 * 471 *
472 * To create a Precision, use one of the factory methods. 473 * 474 * @stable ICU 60 475 */ 476 class U_I18N_API Precision : public UMemory { 477 478 public: 479 /** 480 * Show all available digits to full precision. 481 * 482 *
483 * NOTE: When formatting a double, this method, along with {@link #minFraction} and 484 * {@link #minSignificantDigits}, will trigger complex algorithm similar to Dragon4 to determine the 485 * low-order digits and the number of digits to display based on the value of the double. 486 * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction} 487 * or {@link #maxSignificantDigits} instead to maximize performance. 488 * For more information, read the following blog post. 489 * 490 *
491 * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/ 492 * 493 * @return A Precision for chaining or passing to the NumberFormatter precision() setter. 494 * @stable ICU 60 495 */ 496 static Precision unlimited(); 497 498 /** 499 * Show numbers rounded if necessary to the nearest integer. 500 * 501 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 502 * @stable ICU 60 503 */ 504 static FractionPrecision integer(); 505 506 /** 507 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 508 * Additionally, pad with zeros to ensure that this number of places are always shown. 509 * 510 *
511 * Example output with minMaxFractionPlaces = 3: 512 * 513 *
514 * 87,650.000 515 * 8,765.000 516 * 876.500 517 * 87.650 518 * 8.765 519 * 0.876 520 * 0.088 521 * 0.009 522 * 0.000 (zero) 523 * 524 *
525 * This method is equivalent to {@link #minMaxFraction} with both arguments equal. 526 * 527 * @param minMaxFractionPlaces 528 * The minimum and maximum number of numerals to display after the decimal separator (rounding if too 529 * long or padding with zeros if too short). 530 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 531 * @stable ICU 60 532 */ 533 static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces); 534 535 /** 536 * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if 537 * necessary. Do not perform rounding (display numbers to their full precision). 538 * 539 *
540 * NOTE: If you are formatting doubles, see the performance note in {@link #unlimited}. 541 * 542 * @param minFractionPlaces 543 * The minimum number of numerals to display after the decimal separator (padding with zeros if 544 * necessary). 545 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 546 * @stable ICU 60 547 */ 548 static FractionPrecision minFraction(int32_t minFractionPlaces); 549 550 /** 551 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 552 * Unlike the other fraction rounding strategies, this strategy does not pad zeros to the end of the 553 * number. 554 * 555 * @param maxFractionPlaces 556 * The maximum number of numerals to display after the decimal mark (rounding if necessary). 557 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 558 * @stable ICU 60 559 */ 560 static FractionPrecision maxFraction(int32_t maxFractionPlaces); 561 562 /** 563 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator); 564 * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if 565 * necessary. 566 * 567 * @param minFractionPlaces 568 * The minimum number of numerals to display after the decimal separator (padding with zeros if 569 * necessary). 570 * @param maxFractionPlaces 571 * The maximum number of numerals to display after the decimal separator (rounding if necessary). 572 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 573 * @stable ICU 60 574 */ 575 static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces); 576 577 /** 578 * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally, 579 * pad with zeros to ensure that this number of significant digits/figures are always shown. 580 * 581 *
582 * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal. 583 * 584 * @param minMaxSignificantDigits 585 * The minimum and maximum number of significant digits to display (rounding if too long or padding with 586 * zeros if too short). 587 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 588 * @stable ICU 62 589 */ 590 static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits); 591 592 /** 593 * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not 594 * perform rounding (display numbers to their full precision). 595 * 596 *
597 * NOTE: If you are formatting doubles, see the performance note in {@link #unlimited}. 598 * 599 * @param minSignificantDigits 600 * The minimum number of significant digits to display (padding with zeros if too short). 601 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 602 * @stable ICU 62 603 */ 604 static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits); 605 606 /** 607 * Show numbers rounded if necessary to a certain number of significant digits/figures. 608 * 609 * @param maxSignificantDigits 610 * The maximum number of significant digits to display (rounding if too long). 611 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 612 * @stable ICU 62 613 */ 614 static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits); 615 616 /** 617 * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at 618 * least a certain number of significant digits, padding with zeros if necessary. 619 * 620 * @param minSignificantDigits 621 * The minimum number of significant digits to display (padding with zeros if necessary). 622 * @param maxSignificantDigits 623 * The maximum number of significant digits to display (rounding if necessary). 624 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 625 * @stable ICU 62 626 */ 627 static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits, 628 int32_t maxSignificantDigits); 629 630 /** 631 * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the 632 * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5. 633 * 634 *
635 * In order to ensure that numbers are padded to the appropriate number of fraction places, call 636 * withMinFraction() on the return value of this method. 637 * For example, to round to the nearest 0.5 and always display 2 numerals after the 638 * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run: 639 * 640 *
641 * Precision::increment(0.5).withMinFraction(2) 642 *
657 * Precision::incrementExact(5, -1).withMinFraction(2) 658 * Precision::incrementExact(50, -2).withMinFraction(2) 659 * Precision::incrementExact(50, -2) 660 *
Precision::fixedFraction(2)
Precision::integer()
Precision::increment(0.05)
683 * The exact rounding details will be resolved at runtime based on the currency unit specified in the 684 * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another 685 * currency, the withCurrency() method can be called on the return value of this method. 686 * 687 * @param currencyUsage 688 * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may 689 * be limited by the available denominations of cash or coins). 690 * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter. 691 * @stable ICU 60 692 */ 693 static CurrencyPrecision currency(UCurrencyUsage currencyUsage); 694 695 /** 696 * Configure how trailing zeros are displayed on numbers. For example, to hide trailing zeros 697 * when the number is an integer, use UNUM_TRAILING_ZERO_HIDE_IF_WHOLE. 698 * 699 * @param trailingZeroDisplay Option to configure the display of trailing zeros. 700 * @stable ICU 69 701 */ 702 Precision trailingZeroDisplay(UNumberTrailingZeroDisplay trailingZeroDisplay) const; 703 704 private: 705 enum PrecisionType { 706 RND_BOGUS, 707 RND_NONE, 708 RND_FRACTION, 709 RND_SIGNIFICANT, 710 RND_FRACTION_SIGNIFICANT, 711 712 // Used for strange increments like 3.14. 713 RND_INCREMENT, 714 715 // Used for increments with 1 as the only digit. This is different than fraction 716 // rounding because it supports having additional trailing zeros. For example, this 717 // class is used to round with the increment 0.010. 718 RND_INCREMENT_ONE, 719 720 // Used for increments with 5 as the only digit (nickel rounding). 721 RND_INCREMENT_FIVE, 722 723 RND_CURRENCY, 724 RND_ERROR 725 } fType; 726 727 union PrecisionUnion { 728 /** @internal (private) */ 729 struct FractionSignificantSettings { 730 // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT 731 /** @internal (private) */ 732 impl::digits_t fMinFrac; 733 /** @internal (private) */ 734 impl::digits_t fMaxFrac; 735 /** @internal (private) */ 736 impl::digits_t fMinSig; 737 /** @internal (private) */ 738 impl::digits_t fMaxSig; 739 /** @internal (private) */ 740 UNumberRoundingPriority fPriority; 741 /** 742 * Whether to retain trailing zeros based on the looser strategy. 743 * @internal (private) 744 */ 745 bool fRetain; 746 } fracSig; 747 /** @internal (private) */ 748 struct IncrementSettings { 749 // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE 750 // Note: This is a union, so we shouldn't own memory, since 751 // the default destructor would leak it. 752 /** @internal (private) */ 753 uint64_t fIncrement; 754 /** @internal (private) */ 755 impl::digits_t fIncrementMagnitude; 756 /** @internal (private) */ 757 impl::digits_t fMinFrac; 758 } increment; 759 UCurrencyUsage currencyUsage; // For RND_CURRENCY 760 UErrorCode errorCode; // For RND_ERROR 761 } fUnion; 762 763 UNumberTrailingZeroDisplay fTrailingZeroDisplay = UNUM_TRAILING_ZERO_AUTO; 764 765 typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings; 766 typedef PrecisionUnion::IncrementSettings IncrementSettings; 767 768 Precision(const PrecisionType& type, const PrecisionUnion& union_) 769 : fType(type), fUnion(union_) {} 770 771 Precision(UErrorCode errorCode) : fType(RND_ERROR) { 772 fUnion.errorCode = errorCode; 773 } 774 775 Precision() : fType(RND_BOGUS) {} 776 777 bool isBogus() const { 778 return fType == RND_BOGUS; 779 } 780 781 UBool copyErrorTo(UErrorCode &status) const { 782 if (fType == RND_ERROR) { 783 status = fUnion.errorCode; 784 return true; 785 } 786 return false; 787 } 788 789 // On the parent type so that this method can be called internally on Precision instances. 790 Precision withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const; 791 792 static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac); 793 794 static Precision constructSignificant(int32_t minSig, int32_t maxSig); 795 796 static Precision constructFractionSignificant( 797 const FractionPrecision &base, 798 int32_t minSig, 799 int32_t maxSig, 800 UNumberRoundingPriority priority, 801 bool retain); 802 803 static IncrementPrecision constructIncrement(uint64_t increment, impl::digits_t magnitude); 804 805 static CurrencyPrecision constructCurrency(UCurrencyUsage usage); 806 807 // To allow MacroProps/MicroProps to initialize bogus instances: 808 friend struct impl::MacroProps; 809 friend struct impl::MicroProps; 810 811 // To allow NumberFormatterImpl to access isBogus() and other internal methods: 812 friend class impl::NumberFormatterImpl; 813 814 // To allow NumberPropertyMapper to create instances from DecimalFormatProperties: 815 friend class impl::NumberPropertyMapper; 816 817 // To allow access to the main implementation class: 818 friend class impl::RoundingImpl; 819 820 // To allow child classes to call private methods: 821 friend class FractionPrecision; 822 friend class CurrencyPrecision; 823 friend class IncrementPrecision; 824 825 // To allow access to the skeleton generation code: 826 friend class impl::GeneratorHelpers; 827 828 // To allow access to isBogus and the default (bogus) constructor: 829 friend class units::UnitsRouter; 830 }; 831 832 /** 833 * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be 834 * used when formatting numbers in NumberFormatter. 835 * 836 *
837 * To create a FractionPrecision, use one of the factory methods on Precision. 838 * 839 * @stable ICU 60 840 */ 841 class U_I18N_API FractionPrecision : public Precision { 842 public: 843 /** 844 * Override maximum fraction digits with maximum significant digits depending on the magnitude 845 * of the number. See UNumberRoundingPriority. 846 * 847 * @param minSignificantDigits 848 * Pad trailing zeros to achieve this minimum number of significant digits. 849 * @param maxSignificantDigits 850 * Round the number to achieve this maximum number of significant digits. 851 * @param priority 852 * How to disambiguate between fraction digits and significant digits. 853 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 854 * 855 * @stable ICU 69 856 */ 857 Precision withSignificantDigits( 858 int32_t minSignificantDigits, 859 int32_t maxSignificantDigits, 860 UNumberRoundingPriority priority) const; 861 862 /** 863 * Ensure that no less than this number of significant digits are retained when rounding 864 * according to fraction rules. 865 * 866 * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum 867 * figures set to 2, 3.141 becomes "3.1" instead. 868 * 869 * This setting does not affect the number of trailing zeros. For example, 3.01 would print as 870 * "3", not "3.0". 871 * 872 * This is equivalent to `withSignificantDigits(1, minSignificantDigits, RELAXED)`. 873 * 874 * @param minSignificantDigits 875 * The number of significant figures to guarantee. 876 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 877 * @stable ICU 60 878 */ 879 Precision withMinDigits(int32_t minSignificantDigits) const; 880 881 /** 882 * Ensure that no more than this number of significant digits are retained when rounding 883 * according to fraction rules. 884 * 885 * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum 886 * figures set to 2, 123.4 becomes "120" instead. 887 * 888 * This setting does not affect the number of trailing zeros. For example, with fixed fraction 889 * of 2, 123.4 would become "120.00". 890 * 891 * This is equivalent to `withSignificantDigits(1, maxSignificantDigits, STRICT)`. 892 * 893 * @param maxSignificantDigits 894 * Round the number to no more than this number of significant figures. 895 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 896 * @stable ICU 60 897 */ 898 Precision withMaxDigits(int32_t maxSignificantDigits) const; 899 900 private: 901 // Inherit constructor 902 using Precision::Precision; 903 904 // To allow parent class to call this class's constructor: 905 friend class Precision; 906 }; 907 908 /** 909 * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in 910 * NumberFormatter. 911 * 912 *
913 * To create a CurrencyPrecision, use one of the factory methods on Precision. 914 * 915 * @stable ICU 60 916 */ 917 class U_I18N_API CurrencyPrecision : public Precision { 918 public: 919 /** 920 * Associates a currency with this rounding precision. 921 * 922 *
923 * Calling this method is not required, because the currency specified in unit() 924 * is automatically applied to currency rounding precisions. However, 925 * this method enables you to override that automatic association. 926 * 927 *
928 * This method also enables numbers to be formatted using currency rounding rules without explicitly using a 929 * currency format. 930 * 931 * @param currency 932 * The currency to associate with this rounding precision. 933 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 934 * @stable ICU 60 935 */ 936 Precision withCurrency(const CurrencyUnit ¤cy) const; 937 938 private: 939 // Inherit constructor 940 using Precision::Precision; 941 942 // To allow parent class to call this class's constructor: 943 friend class Precision; 944 }; 945 946 /** 947 * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in 948 * NumberFormatter. 949 * 950 *
951 * To create an IncrementPrecision, use one of the factory methods on Precision. 952 * 953 * @stable ICU 60 954 */ 955 class U_I18N_API IncrementPrecision : public Precision { 956 public: 957 /** 958 * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if 959 * necessary. By default, no trailing zeros are added. 960 * 961 *
962 * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00", 963 * "0.50", "1.00", and "1.50". 964 * 965 *
966 * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment. 967 * 968 * @param minFrac The minimum number of digits after the decimal separator. 969 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 970 * @stable ICU 60 971 */ 972 Precision withMinFraction(int32_t minFrac) const; 973 974 private: 975 // Inherit constructor 976 using Precision::Precision; 977 978 // To allow parent class to call this class's constructor: 979 friend class Precision; 980 }; 981 982 /** 983 * A class that defines the strategy for padding and truncating integers before the decimal separator. 984 * 985 *
986 * To create an IntegerWidth, use one of the factory methods. 987 * 988 * @stable ICU 60 989 * @see NumberFormatter 990 */ 991 class U_I18N_API IntegerWidth : public UMemory { 992 public: 993 /** 994 * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator. 995 * 996 *
997 * For example, with minInt=3, the number 55 will get printed as "055". 998 * 999 * @param minInt 1000 * The minimum number of places before the decimal separator. 1001 * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter. 1002 * @stable ICU 60 1003 */ 1004 static IntegerWidth zeroFillTo(int32_t minInt); 1005 1006 /** 1007 * Truncate numbers exceeding a certain number of numerals before the decimal separator. 1008 * 1009 * For example, with maxInt=3, the number 1234 will get printed as "234". 1010 * 1011 * @param maxInt 1012 * The maximum number of places before the decimal separator. maxInt == -1 means no 1013 * truncation. 1014 * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter. 1015 * @stable ICU 60 1016 */ 1017 IntegerWidth truncateAt(int32_t maxInt); 1018 1019 private: 1020 union { 1021 struct { 1022 impl::digits_t fMinInt; 1023 impl::digits_t fMaxInt; 1024 bool fFormatFailIfMoreThanMaxDigits; 1025 } minMaxInt; 1026 UErrorCode errorCode; 1027 } fUnion; 1028 bool fHasError = false; 1029 1030 IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits); 1031 1032 IntegerWidth(UErrorCode errorCode) { // NOLINT 1033 fUnion.errorCode = errorCode; 1034 fHasError = true; 1035 } 1036 1037 IntegerWidth() { // NOLINT 1038 fUnion.minMaxInt.fMinInt = -1; 1039 } 1040 1041 /** Returns the default instance. */ 1042 static IntegerWidth standard() { 1043 return IntegerWidth::zeroFillTo(1); 1044 } 1045 1046 bool isBogus() const { 1047 return !fHasError && fUnion.minMaxInt.fMinInt == -1; 1048 } 1049 1050 UBool copyErrorTo(UErrorCode &status) const { 1051 if (fHasError) { 1052 status = fUnion.errorCode; 1053 return true; 1054 } 1055 return false; 1056 } 1057 1058 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const; 1059 1060 bool operator==(const IntegerWidth& other) const; 1061 1062 // To allow MacroProps/MicroProps to initialize empty instances: 1063 friend struct impl::MacroProps; 1064 friend struct impl::MicroProps; 1065 1066 // To allow NumberFormatterImpl to access isBogus(): 1067 friend class impl::NumberFormatterImpl; 1068 1069 // To allow the use of this class when formatting: 1070 friend class impl::MutablePatternModifier; 1071 friend class impl::ImmutablePatternModifier; 1072 1073 // So that NumberPropertyMapper can create instances 1074 friend class impl::NumberPropertyMapper; 1075 1076 // To allow access to the skeleton generation code: 1077 friend class impl::GeneratorHelpers; 1078 }; 1079 1080 /** 1081 * A class that defines a quantity by which a number should be multiplied when formatting. 1082 * 1083 *
1084 * To create a Scale, use one of the factory methods. 1085 * 1086 * @stable ICU 62 1087 */ 1088 class U_I18N_API Scale : public UMemory { 1089 public: 1090 /** 1091 * Do not change the value of numbers when formatting or parsing. 1092 * 1093 * @return A Scale to prevent any multiplication. 1094 * @stable ICU 62 1095 */ 1096 static Scale none(); 1097 1098 /** 1099 * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit: 1100 * 1101 *
1102 * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2)) 1103 *
1631 * All notation styles will be properly localized with locale data, and all notation styles are compatible with 1632 * units, rounding precisions, and other number formatter settings. 1633 * 1634 *
1635 * Pass this method the return value of a {@link Notation} factory method. For example: 1636 * 1637 *
1638 * NumberFormatter::with().notation(Notation::compactShort()) 1639 *
1681 * NumberFormatter::with().unit(MeasureUnit::getMeter()) 1682 * NumberFormatter::with().unit(MeasureUnit::forIdentifier("foot-per-second", status)) 1683 *
1688 * NumberFormatter::with().unit(CurrencyUnit(u"USD", status)) 1689 *
1694 * NumberFormatter::with().unit(NoUnit.percent()) 1695 *
1756 * NumberFormatter::with() 1757 * .unit(MeasureUnit::getMeter()) 1758 * .perUnit(MeasureUnit::getSecond()) 1759 *
1821 * Pass this method the return value of one of the factory methods on {@link Precision}. For example: 1822 * 1823 *
1824 * NumberFormatter::with().precision(Precision::fixedFraction(2)) 1825 *
1828 * In most cases, the default rounding strategy is to round to 6 fraction places; i.e., 1829 * Precision.maxFraction(6). The exceptions are if compact notation is being used, then the compact 1830 * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency, 1831 * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for 1832 * details). 1833 * 1834 * @param precision 1835 * The rounding precision to use. 1836 * @return The fluent chain. 1837 * @see Precision 1838 * @stable ICU 62 1839 */ 1840 Derived precision(const Precision& precision) const &; 1841 1842 /** 1843 * Overload of precision() for use on an rvalue reference. 1844 * 1845 * @param precision 1846 * The rounding precision to use. 1847 * @return The fluent chain. 1848 * @see #precision 1849 * @stable ICU 62 1850 */ 1851 Derived precision(const Precision& precision) &&; 1852 1853 /** 1854 * Specifies how to determine the direction to round a number when it has more digits than fit in the 1855 * desired precision. When formatting 1.235: 1856 * 1857 *
Precision.maxFraction(6)
1893 * The exact grouping widths will be chosen based on the locale. 1894 * 1895 *
1896 * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example: 1897 * 1898 *
1899 * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2) 1900 *
1933 * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example: 1934 * 1935 *
1936 * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2)) 1937 *
1972 * Pass this method an instance of {@link DecimalFormatSymbols}. For example: 1973 * 1974 *
1975 * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status)) 1976 *
1979 * Note: DecimalFormatSymbols automatically chooses the best numbering system based on the locale. 1980 * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar 1981 * numbering system. 1982 * 1983 *
1984 * Note: The instance of DecimalFormatSymbols will be copied: changes made to the symbols object 1985 * after passing it into the fluent chain will not be seen. 1986 * 1987 *
1988 * Note: Calling this method will override any previously specified DecimalFormatSymbols 1989 * or NumberingSystem. 1990 * 1991 *
1992 * The default is to choose the symbols based on the locale specified in the fluent chain. 1993 * 1994 * @param symbols 1995 * The DecimalFormatSymbols to use. 1996 * @return The fluent chain. 1997 * @see DecimalFormatSymbols 1998 * @stable ICU 60 1999 */ 2000 Derived symbols(const DecimalFormatSymbols &symbols) const &; 2001 2002 /** 2003 * Overload of symbols() for use on an rvalue reference. 2004 * 2005 * @param symbols 2006 * The DecimalFormatSymbols to use. 2007 * @return The fluent chain. 2008 * @see #symbols 2009 * @stable ICU 62 2010 */ 2011 Derived symbols(const DecimalFormatSymbols &symbols) &&; 2012 2013 /** 2014 * Specifies that the given numbering system should be used when fetching symbols. 2015 * 2016 *
2023 * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin 2024 * alphabet numbering system (ASCII digits): 2025 * 2026 *
2027 * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status)) 2028 *
2031 * Note: Calling this method will override any previously specified DecimalFormatSymbols 2032 * or NumberingSystem. 2033 * 2034 *
2035 * The default is to choose the best numbering system for the locale. 2036 * 2037 *
2038 * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods. 2039 * 2040 * @param symbols 2041 * The NumberingSystem to use. 2042 * @return The fluent chain. 2043 * @see NumberingSystem 2044 * @stable ICU 60 2045 */ 2046 Derived adoptSymbols(NumberingSystem *symbols) const &; 2047 2048 /** 2049 * Overload of adoptSymbols() for use on an rvalue reference. 2050 * 2051 * @param symbols 2052 * The NumberingSystem to use. 2053 * @return The fluent chain. 2054 * @see #adoptSymbols 2055 * @stable ICU 62 2056 */ 2057 Derived adoptSymbols(NumberingSystem *symbols) &&; 2058 2059 /** 2060 * Sets the width of the unit (measure unit or currency). Most common values: 2061 * 2062 *
2069 * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example: 2070 * 2071 *
2072 * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME) 2073 *
2076 * The default is the SHORT width. 2077 * 2078 * @param width 2079 * The width to use when rendering numbers. 2080 * @return The fluent chain 2081 * @see UNumberUnitWidth 2082 * @stable ICU 60 2083 */ 2084 Derived unitWidth(UNumberUnitWidth width) const &; 2085 2086 /** 2087 * Overload of unitWidth() for use on an rvalue reference. 2088 * 2089 * @param width 2090 * The width to use when rendering numbers. 2091 * @return The fluent chain. 2092 * @see #unitWidth 2093 * @stable ICU 62 2094 */ 2095 Derived unitWidth(UNumberUnitWidth width) &&; 2096 2097 /** 2098 * Sets the plus/minus sign display strategy. Most common values: 2099 * 2100 *
2107 * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example: 2108 * 2109 *
2110 * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) 2111 *
2114 * The default is AUTO sign display. 2115 * 2116 * @param style 2117 * The sign display strategy to use when rendering numbers. 2118 * @return The fluent chain 2119 * @see UNumberSignDisplay 2120 * @stable ICU 60 2121 */ 2122 Derived sign(UNumberSignDisplay style) const &; 2123 2124 /** 2125 * Overload of sign() for use on an rvalue reference. 2126 * 2127 * @param style 2128 * The sign display strategy to use when rendering numbers. 2129 * @return The fluent chain. 2130 * @see #sign 2131 * @stable ICU 62 2132 */ 2133 Derived sign(UNumberSignDisplay style) &&; 2134 2135 /** 2136 * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common 2137 * values: 2138 * 2139 *
2145 * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example: 2146 * 2147 *
2148 * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS) 2149 *
2152 * The default is AUTO decimal separator display. 2153 * 2154 * @param style 2155 * The decimal separator display strategy to use when rendering numbers. 2156 * @return The fluent chain 2157 * @see UNumberDecimalSeparatorDisplay 2158 * @stable ICU 60 2159 */ 2160 Derived decimal(UNumberDecimalSeparatorDisplay style) const &; 2161 2162 /** 2163 * Overload of decimal() for use on an rvalue reference. 2164 * 2165 * @param style 2166 * The decimal separator display strategy to use when rendering numbers. 2167 * @return The fluent chain. 2168 * @see #decimal 2169 * @stable ICU 62 2170 */ 2171 Derived decimal(UNumberDecimalSeparatorDisplay style) &&; 2172 2173 /** 2174 * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting. 2175 * Most common values: 2176 * 2177 *
2183 * Pass an element from a {@link Scale} factory method to this setter. For example: 2184 * 2185 *
2186 * NumberFormatter::with().scale(Scale::powerOfTen(2)) 2187 *
2190 * The default is to not apply any multiplier. 2191 * 2192 * @param scale 2193 * The scale to apply when rendering numbers. 2194 * @return The fluent chain 2195 * @stable ICU 62 2196 */ 2197 Derived scale(const Scale &scale) const &; 2198 2199 /** 2200 * Overload of scale() for use on an rvalue reference. 2201 * 2202 * @param scale 2203 * The scale to apply when rendering numbers. 2204 * @return The fluent chain. 2205 * @see #scale 2206 * @stable ICU 62 2207 */ 2208 Derived scale(const Scale &scale) &&; 2209 2210 /** 2211 * Specifies the usage for which numbers will be formatted ("person-height", 2212 * "road", "rainfall", etc.) 2213 * 2214 * When a `usage` is specified, the output unit will change depending on the 2215 * `Locale` and the unit quantity. For example, formatting length 2216 * measurements specified in meters: 2217 * 2218 * `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")` 2219 * * When formatting 0.25, the output will be "10 inches". 2220 * * When formatting 1.50, the output will be "4 feet and 11 inches". 2221 * 2222 * The input unit specified via unit() determines the type of measurement 2223 * being formatted (e.g. "length" when the unit is "foot"). The usage 2224 * requested will be looked for only within this category of measurement 2225 * units. 2226 * 2227 * The output unit can be found via FormattedNumber::getOutputUnit(). 2228 * 2229 * If the usage has multiple parts (e.g. "land-agriculture-grain") and does 2230 * not match a known usage preference, the last part will be dropped 2231 * repeatedly until a match is found (e.g. trying "land-agriculture", then 2232 * "land"). If a match is still not found, usage will fall back to 2233 * "default". 2234 * 2235 * Setting usage to an empty string clears the usage (disables usage-based 2236 * localized formatting). 2237 * 2238 * Setting a usage string but not a correct input unit will result in an 2239 * U_ILLEGAL_ARGUMENT_ERROR. 2240 * 2241 * When using usage, specifying rounding or precision is unnecessary. 2242 * Specifying a precision in some manner will override the default 2243 * formatting. 2244 * 2245 * @param usage A `usage` parameter from the units resource. See the 2246 * unitPreferenceData in *source/data/misc/units.txt*, generated from 2247 * `unitPreferenceData` in [CLDR's 2248 * supplemental/units.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/units.xml). 2249 * @return The fluent chain. 2250 * @stable ICU 68 2251 */ 2252 Derived usage(StringPiece usage) const &; 2253 2254 /** 2255 * Overload of usage() for use on an rvalue reference. 2256 * 2257 * @param usage The unit `usage`. 2258 * @return The fluent chain. 2259 * @stable ICU 68 2260 */ 2261 Derived usage(StringPiece usage) &&; 2262 2263 /** 2264 * Specifies the DisplayOptions. For example, UDisplayOptionsGrammaticalCase specifies 2265 * the desired case for a unit formatter's output (e.g. accusative, dative, genitive). 2266 * 2267 * @param displayOptions 2268 * @return The fluent chain. 2269 * @stable ICU 72 2270 */ 2271 Derived displayOptions(const DisplayOptions &displayOptions) const &; 2272 2273 /** 2274 * Overload of displayOptions() for use on an rvalue reference. 2275 * 2276 * @param displayOptions 2277 * @return The fluent chain. 2278 * @stable ICU 72 2279 */ 2280 Derived displayOptions(const DisplayOptions &displayOptions) &&; 2281 2282 #ifndef U_HIDE_INTERNAL_API 2283 /** 2284 * NOTE: Use `displayOptions` instead. This method was part of 2285 * an internal technology preview in ICU 69, but will be removed 2286 * in ICU 73, in favor of `displayOptions` 2287 * 2288 * Specifies the desired case for a unit formatter's output (e.g. 2289 * accusative, dative, genitive). 2290 * 2291 * @internal 2292 */ 2293 Derived unitDisplayCase(StringPiece unitDisplayCase) const &; 2294 2295 /** 2296 * NOTE: Use `displayOptions` instead. This method was part of 2297 * an internal technology preview in ICU 69, but will be removed 2298 * in ICU 73, in favor of `displayOptions` 2299 * 2300 * Overload of unitDisplayCase() for use on an rvalue reference. 2301 * 2302 * @internal 2303 */ 2304 Derived unitDisplayCase(StringPiece unitDisplayCase) &&; 2305 #endif // U_HIDE_INTERNAL_API 2306 2307 #ifndef U_HIDE_INTERNAL_API 2308 2309 /** 2310 * Set the padding strategy. May be added in the future; see #13338. 2311 * 2312 * @internal ICU 60: This API is ICU internal only. 2313 */ 2314 Derived padding(const impl::Padder &padder) const &; 2315 2316 /** @internal */ 2317 Derived padding(const impl::Padder &padder) &&; 2318 2319 /** 2320 * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to 2321 * be built right away. A threshold of 0 prevents the data structures from being built. 2322 * 2323 * @internal ICU 60: This API is ICU internal only. 2324 */ 2325 Derived threshold(int32_t threshold) const &; 2326 2327 /** @internal */ 2328 Derived threshold(int32_t threshold) &&; 2329 2330 /** 2331 * Internal fluent setter to overwrite the entire macros object. 2332 * 2333 * @internal ICU 60: This API is ICU internal only. 2334 */ 2335 Derived macros(const impl::MacroProps& macros) const &; 2336 2337 /** @internal */ 2338 Derived macros(const impl::MacroProps& macros) &&; 2339 2340 /** @internal */ 2341 Derived macros(impl::MacroProps&& macros) const &; 2342 2343 /** @internal */ 2344 Derived macros(impl::MacroProps&& macros) &&; 2345 2346 #endif /* U_HIDE_INTERNAL_API */ 2347 2348 /** 2349 * Creates a skeleton string representation of this number formatter. A skeleton string is a 2350 * locale-agnostic serialized form of a number formatter. 2351 * 2352 * Not all options are capable of being represented in the skeleton string; for example, a 2353 * DecimalFormatSymbols object. If any such option is encountered, the error code is set to 2354 * U_UNSUPPORTED_ERROR. 2355 * 2356 * The returned skeleton is in normalized form, such that two number formatters with equivalent 2357 * behavior should produce the same skeleton. 2358 * 2359 * For more information on number skeleton strings, see: 2360 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2361 * 2362 * @return A number skeleton string with behavior corresponding to this number formatter. 2363 * @stable ICU 62 2364 */ 2365 UnicodeString toSkeleton(UErrorCode& status) const; 2366 2367 /** 2368 * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer 2369 * wrapping a heap-allocated copy of the current object. 2370 * 2371 * This is equivalent to new-ing the move constructor with a value object 2372 * as the argument. 2373 * 2374 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped 2375 * nullptr on failure. 2376 * @stable ICU 64 2377 */ 2378 LocalPointer clone() const &; 2379 2380 /** 2381 * Overload of clone for use on an rvalue reference. 2382 * 2383 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped 2384 * nullptr on failure. 2385 * @stable ICU 64 2386 */ 2387 LocalPointer clone() &&; 2388 2389 /** 2390 * Sets the UErrorCode if an error occurred in the fluent chain. 2391 * Preserves older error codes in the outErrorCode. 2392 * @return true if U_FAILURE(outErrorCode) 2393 * @stable ICU 60 2394 */ 2395 UBool copyErrorTo(UErrorCode &outErrorCode) const { 2396 if (U_FAILURE(outErrorCode)) { 2397 // Do not overwrite the older error code 2398 return true; 2399 } 2400 fMacros.copyErrorTo(outErrorCode); 2401 return U_FAILURE(outErrorCode); 2402 } 2403 2404 // NOTE: Uses default copy and move constructors. 2405 2406 private: 2407 impl::MacroProps fMacros; 2408 2409 // Don't construct me directly! Use (Un)LocalizedNumberFormatter. 2410 NumberFormatterSettings() = default; 2411 2412 friend class LocalizedNumberFormatter; 2413 friend class UnlocalizedNumberFormatter; 2414 2415 // Give NumberRangeFormatter access to the MacroProps 2416 friend void impl::touchRangeLocales(impl::RangeMacroProps& macros); 2417 friend class impl::NumberRangeFormatterImpl; 2418 }; 2419 2420 // Explicit instantiations in source/i18n/number_fluent.cpp. 2421 // (MSVC treats imports/exports of explicit instantiations differently.) 2422 #ifndef _MSC_VER 2423 extern template class NumberFormatterSettings; 2424 extern template class NumberFormatterSettings; 2425 #endif 2426 2427 /** 2428 * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified. 2429 * 2430 * Instances of this class are immutable and thread-safe. 2431 * 2432 * @see NumberFormatter 2433 * @stable ICU 60 2434 */ 2435 class U_I18N_API UnlocalizedNumberFormatter 2436 : public NumberFormatterSettings, public UMemory { 2437 2438 public: 2439 /** 2440 * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols, 2441 * formats, and other data for number display. 2442 * 2443 * @param locale 2444 * The locale to use when loading data for number formatting. 2445 * @return The fluent chain. 2446 * @stable ICU 60 2447 */ 2448 LocalizedNumberFormatter locale(const icu::Locale &locale) const &; 2449 2450 /** 2451 * Overload of locale() for use on an rvalue reference. 2452 * 2453 * @param locale 2454 * The locale to use when loading data for number formatting. 2455 * @return The fluent chain. 2456 * @see #locale 2457 * @stable ICU 62 2458 */ 2459 LocalizedNumberFormatter locale(const icu::Locale &locale) &&; 2460 2461 /** 2462 * Default constructor: puts the formatter into a valid but undefined state. 2463 * 2464 * @stable ICU 62 2465 */ 2466 UnlocalizedNumberFormatter() = default; 2467 2468 /** 2469 * Returns a copy of this UnlocalizedNumberFormatter. 2470 * @stable ICU 60 2471 */ 2472 UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other); 2473 2474 /** 2475 * Move constructor: 2476 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. 2477 * @stable ICU 62 2478 */ 2479 UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) noexcept; 2480 2481 /** 2482 * Copy assignment operator. 2483 * @stable ICU 62 2484 */ 2485 UnlocalizedNumberFormatter& operator=(const UnlocalizedNumberFormatter& other); 2486 2487 /** 2488 * Move assignment operator: 2489 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. 2490 * @stable ICU 62 2491 */ 2492 UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) noexcept; 2493 2494 private: 2495 explicit UnlocalizedNumberFormatter(const NumberFormatterSettings& other); 2496 2497 explicit UnlocalizedNumberFormatter( 2498 NumberFormatterSettings&& src) noexcept; 2499 2500 // To give the fluent setters access to this class's constructor: 2501 friend class NumberFormatterSettings; 2502 2503 // To give NumberFormatter::with() access to this class's constructor: 2504 friend class NumberFormatter; 2505 }; 2506 2507 /** 2508 * A NumberFormatter that has a locale associated with it; this means .format() methods are available. 2509 * 2510 * Instances of this class are immutable and thread-safe. 2511 * 2512 * @see NumberFormatter 2513 * @stable ICU 60 2514 */ 2515 class U_I18N_API LocalizedNumberFormatter 2516 : public NumberFormatterSettings, public UMemory { 2517 public: 2518 /** 2519 * Format the given integer number to a string using the settings specified in the NumberFormatter fluent 2520 * setting chain. 2521 * 2522 * @param value 2523 * The number to format. 2524 * @param status 2525 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2526 * @return A FormattedNumber object; call .toString() to get the string. 2527 * @stable ICU 60 2528 */ 2529 FormattedNumber formatInt(int64_t value, UErrorCode &status) const; 2530 2531 /** 2532 * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting 2533 * chain. 2534 * 2535 * @param value 2536 * The number to format. 2537 * @param status 2538 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2539 * @return A FormattedNumber object; call .toString() to get the string. 2540 * @stable ICU 60 2541 */ 2542 FormattedNumber formatDouble(double value, UErrorCode &status) const; 2543 2544 /** 2545 * Format the given decimal number to a string using the settings 2546 * specified in the NumberFormatter fluent setting chain. 2547 * The syntax of the unformatted number is a "numeric string" 2548 * as defined in the Decimal Arithmetic Specification, available at 2549 * http://speleotrove.com/decimal 2550 * 2551 * @param value 2552 * The number to format. 2553 * @param status 2554 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2555 * @return A FormattedNumber object; call .toString() to get the string. 2556 * @stable ICU 60 2557 */ 2558 FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const; 2559 2560 #ifndef U_HIDE_INTERNAL_API 2561 2562 2563 /** 2564 * @internal 2565 */ 2566 const DecimalFormatSymbols* getDecimalFormatSymbols() const; 2567 2568 /** Internal method. 2569 * @internal 2570 */ 2571 FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const; 2572 2573 /** Internal method for DecimalFormat compatibility. 2574 * @internal 2575 */ 2576 void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString& result, UErrorCode& status) const; 2577 2578 /** 2579 * Internal method for testing. 2580 * @internal 2581 */ 2582 const impl::NumberFormatterImpl* getCompiled() const; 2583 2584 /** 2585 * Internal method for testing. 2586 * @internal 2587 */ 2588 int32_t getCallCount() const; 2589 2590 #endif /* U_HIDE_INTERNAL_API */ 2591 2592 /** 2593 * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use 2594 * of this number formatter with APIs that need an object of that type, such as MessageFormat. 2595 * 2596 * This API is not intended to be used other than for enabling API compatibility. The formatDouble, 2597 * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format 2598 * object returned by this method. 2599 * 2600 * The caller owns the returned object and must delete it when finished. 2601 * 2602 * @return A Format wrapping this LocalizedNumberFormatter. 2603 * @stable ICU 62 2604 */ 2605 Format* toFormat(UErrorCode& status) const; 2606 2607 /** 2608 * Default constructor: puts the formatter into a valid but undefined state. 2609 * 2610 * @stable ICU 62 2611 */ 2612 LocalizedNumberFormatter() = default; 2613 2614 /** 2615 * Returns a copy of this LocalizedNumberFormatter. 2616 * @stable ICU 60 2617 */ 2618 LocalizedNumberFormatter(const LocalizedNumberFormatter &other); 2619 2620 /** 2621 * Move constructor: 2622 * The source LocalizedNumberFormatter will be left in a valid but undefined state. 2623 * @stable ICU 62 2624 */ 2625 LocalizedNumberFormatter(LocalizedNumberFormatter&& src) noexcept; 2626 2627 /** 2628 * Copy assignment operator. 2629 * @stable ICU 62 2630 */ 2631 LocalizedNumberFormatter& operator=(const LocalizedNumberFormatter& other); 2632 2633 /** 2634 * Move assignment operator: 2635 * The source LocalizedNumberFormatter will be left in a valid but undefined state. 2636 * @stable ICU 62 2637 */ 2638 LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) noexcept; 2639 2640 #ifndef U_HIDE_INTERNAL_API 2641 2642 /** 2643 * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path 2644 * for the first few calls, and compiling a more efficient data structure if called repeatedly. 2645 * 2646 * 2647 * This function is very hot, being called in every call to the number formatting pipeline. 2648 * 2649 * @param results 2650 * The results object. This method will mutate it to save the results. 2651 * @param status 2652 * @internal 2653 */ 2654 void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const; 2655 2656 #endif /* U_HIDE_INTERNAL_API */ 2657 2658 /** 2659 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own. 2660 * @stable ICU 60 2661 */ 2662 ~LocalizedNumberFormatter(); 2663 2664 private: 2665 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal 2666 // header, and LocalPointer needs the full class definition in order to delete the instance. 2667 const impl::NumberFormatterImpl* fCompiled {nullptr}; 2668 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t 2669 2670 // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter 2671 // from a DecimalFormat. 2672 const impl::DecimalFormatWarehouse* fWarehouse {nullptr}; 2673 2674 explicit LocalizedNumberFormatter(const NumberFormatterSettings& other); 2675 2676 explicit LocalizedNumberFormatter(NumberFormatterSettings&& src) noexcept; 2677 2678 LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale); 2679 2680 LocalizedNumberFormatter(impl::MacroProps &¯os, const Locale &locale); 2681 2682 void resetCompiled(); 2683 2684 void lnfMoveHelper(LocalizedNumberFormatter&& src); 2685 2686 void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status); 2687 2688 /** 2689 * @return true if the compiled formatter is available. 2690 */ 2691 bool computeCompiled(UErrorCode& status) const; 2692 2693 // To give the fluent setters access to this class's constructor: 2694 friend class NumberFormatterSettings; 2695 friend class NumberFormatterSettings; 2696 2697 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor: 2698 friend class UnlocalizedNumberFormatter; 2699 }; 2700 2701 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) 2702 // Warning 4661. 2703 #pragma warning(pop) 2704 #endif 2705 2706 /** 2707 * See the main description in numberformatter.h for documentation and examples. 2708 * 2709 * @stable ICU 60 2710 */ 2711 class U_I18N_API NumberFormatter final { 2712 public: 2713 /** 2714 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at 2715 * the call site. 2716 * 2717 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining. 2718 * @stable ICU 60 2719 */ 2720 static UnlocalizedNumberFormatter with(); 2721 2722 /** 2723 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call 2724 * site. 2725 * 2726 * @param locale 2727 * The locale from which to load formats and symbols for number formatting. 2728 * @return A {@link LocalizedNumberFormatter}, to be used for chaining. 2729 * @stable ICU 60 2730 */ 2731 static LocalizedNumberFormatter withLocale(const Locale &locale); 2732 2733 /** 2734 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2735 * on a given number skeleton string. 2736 * 2737 * It is possible for an error to occur while parsing. See the overload of this method if you are 2738 * interested in the location of a possible parse error. 2739 * 2740 * For more information on number skeleton strings, see: 2741 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2742 * 2743 * @param skeleton 2744 * The skeleton string off of which to base this NumberFormatter. 2745 * @param status 2746 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2747 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2748 * @stable ICU 62 2749 */ 2750 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status); 2751 2752 /** 2753 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2754 * on a given number skeleton string. 2755 * 2756 * If an error occurs while parsing the skeleton string, the offset into the skeleton string at 2757 * which the error occurred will be saved into the UParseError, if provided. 2758 * 2759 * For more information on number skeleton strings, see: 2760 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2761 * 2762 * @param skeleton 2763 * The skeleton string off of which to base this NumberFormatter. 2764 * @param perror 2765 * A parse error struct populated if an error occurs when parsing. 2766 * If no error occurs, perror.offset will be set to -1. 2767 * @param status 2768 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2769 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2770 * @stable ICU 64 2771 */ 2772 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, 2773 UParseError& perror, UErrorCode& status); 2774 2775 /** 2776 * Use factory methods instead of the constructor to create a NumberFormatter. 2777 */ 2778 NumberFormatter() = delete; 2779 }; 2780 2781 } // namespace number 2782 U_NAMESPACE_END 2783 2784 #endif /* #if !UCONFIG_NO_FORMATTING */ 2785 2786 #endif /* U_SHOW_CPLUSPLUS_API */ 2787 2788 #endif // __NUMBERFORMATTER_H__
2647 * This function is very hot, being called in every call to the number formatting pipeline. 2648 * 2649 * @param results 2650 * The results object. This method will mutate it to save the results. 2651 * @param status 2652 * @internal 2653 */ 2654 void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const; 2655 2656 #endif /* U_HIDE_INTERNAL_API */ 2657 2658 /** 2659 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own. 2660 * @stable ICU 60 2661 */ 2662 ~LocalizedNumberFormatter(); 2663 2664 private: 2665 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal 2666 // header, and LocalPointer needs the full class definition in order to delete the instance. 2667 const impl::NumberFormatterImpl* fCompiled {nullptr}; 2668 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t 2669 2670 // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter 2671 // from a DecimalFormat. 2672 const impl::DecimalFormatWarehouse* fWarehouse {nullptr}; 2673 2674 explicit LocalizedNumberFormatter(const NumberFormatterSettings& other); 2675 2676 explicit LocalizedNumberFormatter(NumberFormatterSettings&& src) noexcept; 2677 2678 LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale); 2679 2680 LocalizedNumberFormatter(impl::MacroProps &¯os, const Locale &locale); 2681 2682 void resetCompiled(); 2683 2684 void lnfMoveHelper(LocalizedNumberFormatter&& src); 2685 2686 void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status); 2687 2688 /** 2689 * @return true if the compiled formatter is available. 2690 */ 2691 bool computeCompiled(UErrorCode& status) const; 2692 2693 // To give the fluent setters access to this class's constructor: 2694 friend class NumberFormatterSettings; 2695 friend class NumberFormatterSettings; 2696 2697 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor: 2698 friend class UnlocalizedNumberFormatter; 2699 }; 2700 2701 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) 2702 // Warning 4661. 2703 #pragma warning(pop) 2704 #endif 2705 2706 /** 2707 * See the main description in numberformatter.h for documentation and examples. 2708 * 2709 * @stable ICU 60 2710 */ 2711 class U_I18N_API NumberFormatter final { 2712 public: 2713 /** 2714 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at 2715 * the call site. 2716 * 2717 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining. 2718 * @stable ICU 60 2719 */ 2720 static UnlocalizedNumberFormatter with(); 2721 2722 /** 2723 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call 2724 * site. 2725 * 2726 * @param locale 2727 * The locale from which to load formats and symbols for number formatting. 2728 * @return A {@link LocalizedNumberFormatter}, to be used for chaining. 2729 * @stable ICU 60 2730 */ 2731 static LocalizedNumberFormatter withLocale(const Locale &locale); 2732 2733 /** 2734 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2735 * on a given number skeleton string. 2736 * 2737 * It is possible for an error to occur while parsing. See the overload of this method if you are 2738 * interested in the location of a possible parse error. 2739 * 2740 * For more information on number skeleton strings, see: 2741 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2742 * 2743 * @param skeleton 2744 * The skeleton string off of which to base this NumberFormatter. 2745 * @param status 2746 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2747 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2748 * @stable ICU 62 2749 */ 2750 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status); 2751 2752 /** 2753 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2754 * on a given number skeleton string. 2755 * 2756 * If an error occurs while parsing the skeleton string, the offset into the skeleton string at 2757 * which the error occurred will be saved into the UParseError, if provided. 2758 * 2759 * For more information on number skeleton strings, see: 2760 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2761 * 2762 * @param skeleton 2763 * The skeleton string off of which to base this NumberFormatter. 2764 * @param perror 2765 * A parse error struct populated if an error occurs when parsing. 2766 * If no error occurs, perror.offset will be set to -1. 2767 * @param status 2768 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2769 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2770 * @stable ICU 64 2771 */ 2772 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, 2773 UParseError& perror, UErrorCode& status); 2774 2775 /** 2776 * Use factory methods instead of the constructor to create a NumberFormatter. 2777 */ 2778 NumberFormatter() = delete; 2779 }; 2780 2781 } // namespace number 2782 U_NAMESPACE_END 2783 2784 #endif /* #if !UCONFIG_NO_FORMATTING */ 2785 2786 #endif /* U_SHOW_CPLUSPLUS_API */ 2787 2788 #endif // __NUMBERFORMATTER_H__