1 // © 2017 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 4 #ifndef __NUMBERFORMATTER_H__ 5 #define __NUMBERFORMATTER_H__ 6 7 #include "unicode/utypes.h" 8 9 #if U_SHOW_CPLUSPLUS_API 10 11 #if !UCONFIG_NO_FORMATTING 12 13 #include "unicode/appendable.h" 14 #include "unicode/bytestream.h" 15 #include "unicode/currunit.h" 16 #include "unicode/dcfmtsym.h" 17 #include "unicode/displayoptions.h" 18 #include "unicode/fieldpos.h" 19 #include "unicode/fpositer.h" 20 #include "unicode/measunit.h" 21 #include "unicode/nounit.h" 22 #include "unicode/parseerr.h" 23 #include "unicode/plurrule.h" 24 #include "unicode/ucurr.h" 25 #include "unicode/unum.h" 26 #include "unicode/unumberformatter.h" 27 #include "unicode/uobject.h" 28 #include "unicode/unumberoptions.h" 29 #include "unicode/formattednumber.h" 30 31 /** 32 * \file 33 * \brief C++ API: All-in-one formatter for localized numbers, currencies, and units. 34 * 35 * For a full list of options, see icu::number::NumberFormatterSettings. 36 * 37 * <pre> 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<UnlocalizedNumberFormatter> 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 * </pre> 64 * 65 * <p> 66 * This API offers more features than DecimalFormat and is geared toward new users of ICU. 67 * 68 * <p> 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 * <pre> 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 * </pre> 78 * 79 * <p> 80 * This API is based on the <em>fluent</em> design pattern popularized by libraries such as Google's Guava. For 81 * extensive details on the design of this API, read <a href="https://goo.gl/szi5VB">the design doc</a>. 82 * 83 * <p> 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::impl { 97 98 // Forward declarations: 99 class NumberParserImpl; 100 class MultiplierParseHandler; 101 102 } // namespace numparse::impl 103 104 namespace units { 105 106 // Forward declarations: 107 class UnitsRouter; 108 109 } // namespace units 110 111 namespace number { // icu::number 112 113 // Forward declarations: 114 class UnlocalizedNumberFormatter; 115 class LocalizedNumberFormatter; 116 class SimpleNumberFormatter; 117 class FormattedNumber; 118 class Notation; 119 class ScientificNotation; 120 class Precision; 121 class FractionPrecision; 122 class CurrencyPrecision; 123 class IncrementPrecision; 124 class IntegerWidth; 125 126 namespace impl { 127 128 // can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes 129 /** 130 * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig. 131 * 132 * @internal 133 */ 134 typedef int16_t digits_t; 135 136 // can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization 137 /** 138 * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built 139 * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path. 140 * 141 * @internal 142 */ 143 static constexpr int32_t kInternalDefaultThreshold = 3; 144 145 // Forward declarations: 146 class Padder; 147 struct MacroProps; 148 struct MicroProps; 149 class DecimalQuantity; 150 class UFormattedNumberData; 151 class NumberFormatterImpl; 152 struct ParsedPatternInfo; 153 class ScientificModifier; 154 class MultiplierProducer; 155 class RoundingImpl; 156 class ScientificHandler; 157 class Modifier; 158 class AffixPatternProvider; 159 class NumberPropertyMapper; 160 struct DecimalFormatProperties; 161 class MultiplierFormatHandler; 162 class CurrencySymbols; 163 class GeneratorHelpers; 164 class DecNum; 165 class NumberRangeFormatterImpl; 166 struct RangeMacroProps; 167 struct UFormattedNumberImpl; 168 class MutablePatternModifier; 169 class ImmutablePatternModifier; 170 struct DecimalFormatWarehouse; 171 struct SimpleMicroProps; 172 class AdoptingSignumModifierStore; 173 174 /** 175 * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp. 176 * Declared here so it can be friended. 177 * 178 * @internal 179 */ 180 void touchRangeLocales(impl::RangeMacroProps& macros); 181 182 } // namespace impl 183 184 /** 185 * Extra name reserved in case it is needed in the future. 186 * 187 * @stable ICU 63 188 */ 189 typedef Notation CompactNotation; 190 191 /** 192 * Extra name reserved in case it is needed in the future. 193 * 194 * @stable ICU 63 195 */ 196 typedef Notation SimpleNotation; 197 198 /** 199 * A class that defines the notation style to be used when formatting numbers in NumberFormatter. 200 * 201 * @stable ICU 60 202 */ 203 class U_I18N_API Notation : public UMemory { 204 public: 205 /** 206 * Print the number using scientific notation (also known as scientific form, standard index form, or standard form 207 * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the 208 * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more 209 * digits after the decimal separator, and the corresponding power of 10 displayed after the "E". 210 * 211 * <p> 212 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3: 213 * 214 * <pre> 215 * 8.765E4 216 * 8.765E3 217 * 8.765E2 218 * 8.765E1 219 * 8.765E0 220 * 8.765E-1 221 * 8.765E-2 222 * 8.765E-3 223 * 0E0 224 * </pre> 225 * 226 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. 227 * @stable ICU 60 228 */ 229 static ScientificNotation scientific(); 230 231 /** 232 * Print the number using engineering notation, a variant of scientific notation in which the exponent must be 233 * divisible by 3. 234 * 235 * <p> 236 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3: 237 * 238 * <pre> 239 * 87.65E3 240 * 8.765E3 241 * 876.5E0 242 * 87.65E0 243 * 8.765E0 244 * 876.5E-3 245 * 87.65E-3 246 * 8.765E-3 247 * 0E0 248 * </pre> 249 * 250 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter. 251 * @stable ICU 60 252 */ 253 static ScientificNotation engineering(); 254 255 /** 256 * Print the number using short-form compact notation. 257 * 258 * <p> 259 * <em>Compact notation</em>, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with 260 * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to 261 * engineering notation in how it scales numbers. 262 * 263 * <p> 264 * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing 265 * screen real estate. 266 * 267 * <p> 268 * In short form, the powers of ten are abbreviated. In <em>en-US</em>, the abbreviations are "K" for thousands, "M" 269 * for millions, "B" for billions, and "T" for trillions. Example outputs in <em>en-US</em> when printing 8.765E7 270 * through 8.765E0: 271 * 272 * <pre> 273 * 88M 274 * 8.8M 275 * 876K 276 * 88K 277 * 8.8K 278 * 876 279 * 88 280 * 8.8 281 * </pre> 282 * 283 * <p> 284 * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest 285 * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal 286 * separator if there is only one digit before the decimal separator. The default compact notation rounding precision 287 * is equivalent to: 288 * 289 * <pre> 290 * Precision::integer().withMinDigits(2) 291 * </pre> 292 * 293 * @return A CompactNotation for passing to the NumberFormatter notation() setter. 294 * @stable ICU 60 295 */ 296 static CompactNotation compactShort(); 297 298 /** 299 * Print the number using long-form compact notation. For more information on compact notation, see 300 * {@link #compactShort}. 301 * 302 * <p> 303 * In long form, the powers of ten are spelled out fully. Example outputs in <em>en-US</em> when printing 8.765E7 304 * through 8.765E0: 305 * 306 * <pre> 307 * 88 million 308 * 8.8 million 309 * 876 thousand 310 * 88 thousand 311 * 8.8 thousand 312 * 876 313 * 88 314 * 8.8 315 * </pre> 316 * 317 * @return A CompactNotation for passing to the NumberFormatter notation() setter. 318 * @stable ICU 60 319 */ 320 static CompactNotation compactLong(); 321 322 /** 323 * Print the number using simple notation without any scaling by powers of ten. This is the default behavior. 324 * 325 * <p> 326 * Since this is the default behavior, this method needs to be called only when it is necessary to override a 327 * previous setting. 328 * 329 * <p> 330 * Example outputs in <em>en-US</em> when printing 8.765E7 through 8.765E0: 331 * 332 * <pre> 333 * 87,650,000 334 * 8,765,000 335 * 876,500 336 * 87,650 337 * 8,765 338 * 876.5 339 * 87.65 340 * 8.765 341 * </pre> 342 * 343 * @return A SimpleNotation for passing to the NumberFormatter notation() setter. 344 * @stable ICU 60 345 */ 346 static SimpleNotation simple(); 347 348 private: 349 enum NotationType { 350 NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR 351 } fType; 352 353 union NotationUnion { 354 // For NTN_SCIENTIFIC 355 /** @internal (private) */ 356 struct ScientificSettings { 357 /** @internal (private) */ 358 int8_t fEngineeringInterval; 359 /** @internal (private) */ 360 bool fRequireMinInt; 361 /** @internal (private) */ 362 impl::digits_t fMinExponentDigits; 363 /** @internal (private) */ 364 UNumberSignDisplay fExponentSignDisplay; 365 } scientific; 366 367 // For NTN_COMPACT 368 UNumberCompactStyle compactStyle; 369 370 // For NTN_ERROR 371 UErrorCode errorCode; 372 } fUnion; 373 374 typedef NotationUnion::ScientificSettings ScientificSettings; 375 Notation(const NotationType & type,const NotationUnion & union_)376 Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {} 377 Notation(UErrorCode errorCode)378 Notation(UErrorCode errorCode) : fType(NTN_ERROR) { 379 fUnion.errorCode = errorCode; 380 } 381 Notation()382 Notation() : fType(NTN_SIMPLE), fUnion() {} 383 copyErrorTo(UErrorCode & status)384 UBool copyErrorTo(UErrorCode &status) const { 385 if (fType == NTN_ERROR) { 386 status = fUnion.errorCode; 387 return true; 388 } 389 return false; 390 } 391 392 // To allow MacroProps to initialize empty instances: 393 friend struct impl::MacroProps; 394 friend class ScientificNotation; 395 396 // To allow implementation to access internal types: 397 friend class impl::NumberFormatterImpl; 398 friend class impl::ScientificModifier; 399 friend class impl::ScientificHandler; 400 401 // To allow access to the skeleton generation code: 402 friend class impl::GeneratorHelpers; 403 }; 404 405 /** 406 * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter. 407 * 408 * <p> 409 * To create a ScientificNotation, use one of the factory methods in {@link Notation}. 410 * 411 * @stable ICU 60 412 */ 413 class U_I18N_API ScientificNotation : public Notation { 414 public: 415 /** 416 * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if 417 * necessary. Useful for fixed-width display. 418 * 419 * <p> 420 * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in <em>en-US</em> instead of 421 * the default "1.23E2". 422 * 423 * @param minExponentDigits 424 * The minimum number of digits to show in the exponent. 425 * @return A ScientificNotation, for chaining. 426 * @stable ICU 60 427 */ 428 ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const; 429 430 /** 431 * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO, 432 * showing the minus sign but not the plus sign. 433 * 434 * <p> 435 * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in <em>en-US</em> 436 * instead of the default "1.23E2". 437 * 438 * @param exponentSignDisplay 439 * The strategy for displaying the sign in the exponent. 440 * @return A ScientificNotation, for chaining. 441 * @stable ICU 60 442 */ 443 ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const; 444 445 private: 446 // Inherit constructor 447 using Notation::Notation; 448 449 // Raw constructor for NumberPropertyMapper 450 ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits, 451 UNumberSignDisplay fExponentSignDisplay); 452 453 friend class Notation; 454 455 // So that NumberPropertyMapper can create instances 456 friend class impl::NumberPropertyMapper; 457 }; 458 459 /** 460 * Extra name reserved in case it is needed in the future. 461 * 462 * @stable ICU 63 463 */ 464 typedef Precision SignificantDigitsPrecision; 465 466 /** 467 * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter. 468 * 469 * <p> 470 * To create a Precision, use one of the factory methods. 471 * 472 * @stable ICU 60 473 */ 474 class U_I18N_API Precision : public UMemory { 475 476 public: 477 /** 478 * Show all available digits to full precision. 479 * 480 * <p> 481 * <strong>NOTE:</strong> When formatting a <em>double</em>, this method, along with {@link #minFraction} and 482 * {@link #minSignificantDigits}, will trigger complex algorithm similar to <em>Dragon4</em> to determine the 483 * low-order digits and the number of digits to display based on the value of the double. 484 * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction} 485 * or {@link #maxSignificantDigits} instead to maximize performance. 486 * For more information, read the following blog post. 487 * 488 * <p> 489 * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/ 490 * 491 * @return A Precision for chaining or passing to the NumberFormatter precision() setter. 492 * @stable ICU 60 493 */ 494 static Precision unlimited(); 495 496 /** 497 * Show numbers rounded if necessary to the nearest integer. 498 * 499 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 500 * @stable ICU 60 501 */ 502 static FractionPrecision integer(); 503 504 /** 505 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 506 * Additionally, pad with zeros to ensure that this number of places are always shown. 507 * 508 * <p> 509 * Example output with minMaxFractionPlaces = 3: 510 * 511 * <p> 512 * 87,650.000<br> 513 * 8,765.000<br> 514 * 876.500<br> 515 * 87.650<br> 516 * 8.765<br> 517 * 0.876<br> 518 * 0.088<br> 519 * 0.009<br> 520 * 0.000 (zero) 521 * 522 * <p> 523 * This method is equivalent to {@link #minMaxFraction} with both arguments equal. 524 * 525 * @param minMaxFractionPlaces 526 * The minimum and maximum number of numerals to display after the decimal separator (rounding if too 527 * long or padding with zeros if too short). 528 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 529 * @stable ICU 60 530 */ 531 static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces); 532 533 /** 534 * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if 535 * necessary. Do not perform rounding (display numbers to their full precision). 536 * 537 * <p> 538 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}. 539 * 540 * @param minFractionPlaces 541 * The minimum number of numerals to display after the decimal separator (padding with zeros if 542 * necessary). 543 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 544 * @stable ICU 60 545 */ 546 static FractionPrecision minFraction(int32_t minFractionPlaces); 547 548 /** 549 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator). 550 * Unlike the other fraction rounding strategies, this strategy does <em>not</em> pad zeros to the end of the 551 * number. 552 * 553 * @param maxFractionPlaces 554 * The maximum number of numerals to display after the decimal mark (rounding if necessary). 555 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 556 * @stable ICU 60 557 */ 558 static FractionPrecision maxFraction(int32_t maxFractionPlaces); 559 560 /** 561 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator); 562 * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if 563 * necessary. 564 * 565 * @param minFractionPlaces 566 * The minimum number of numerals to display after the decimal separator (padding with zeros if 567 * necessary). 568 * @param maxFractionPlaces 569 * The maximum number of numerals to display after the decimal separator (rounding if necessary). 570 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter. 571 * @stable ICU 60 572 */ 573 static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces); 574 575 /** 576 * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally, 577 * pad with zeros to ensure that this number of significant digits/figures are always shown. 578 * 579 * <p> 580 * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal. 581 * 582 * @param minMaxSignificantDigits 583 * The minimum and maximum number of significant digits to display (rounding if too long or padding with 584 * zeros if too short). 585 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 586 * @stable ICU 62 587 */ 588 static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits); 589 590 /** 591 * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not 592 * perform rounding (display numbers to their full precision). 593 * 594 * <p> 595 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}. 596 * 597 * @param minSignificantDigits 598 * The minimum number of significant digits to display (padding with zeros if too short). 599 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 600 * @stable ICU 62 601 */ 602 static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits); 603 604 /** 605 * Show numbers rounded if necessary to a certain number of significant digits/figures. 606 * 607 * @param maxSignificantDigits 608 * The maximum number of significant digits to display (rounding if too long). 609 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 610 * @stable ICU 62 611 */ 612 static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits); 613 614 /** 615 * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at 616 * least a certain number of significant digits, padding with zeros if necessary. 617 * 618 * @param minSignificantDigits 619 * The minimum number of significant digits to display (padding with zeros if necessary). 620 * @param maxSignificantDigits 621 * The maximum number of significant digits to display (rounding if necessary). 622 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 623 * @stable ICU 62 624 */ 625 static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits, 626 int32_t maxSignificantDigits); 627 628 /** 629 * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the 630 * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5. 631 * 632 * <p> 633 * In order to ensure that numbers are padded to the appropriate number of fraction places, call 634 * withMinFraction() on the return value of this method. 635 * For example, to round to the nearest 0.5 and always display 2 numerals after the 636 * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run: 637 * 638 * <pre> 639 * Precision::increment(0.5).withMinFraction(2) 640 * </pre> 641 * 642 * @param roundingIncrement 643 * The increment to which to round numbers. 644 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 645 * @stable ICU 60 646 */ 647 static IncrementPrecision increment(double roundingIncrement); 648 649 /** 650 * Version of `Precision::increment()` that takes an integer at a particular power of 10. 651 * 652 * To round to the nearest 0.5 and display 2 fraction digits, with this function, you should write one of the following: 653 * 654 * <pre> 655 * Precision::incrementExact(5, -1).withMinFraction(2) 656 * Precision::incrementExact(50, -2).withMinFraction(2) 657 * Precision::incrementExact(50, -2) 658 * </pre> 659 * 660 * This is analagous to ICU4J `Precision.increment(new BigDecimal("0.50"))`. 661 * 662 * This behavior is modeled after ECMA-402. For more information, see: 663 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingincrement 664 * 665 * @param mantissa 666 * The increment to which to round numbers. 667 * @param magnitude 668 * The power of 10 of the ones digit of the mantissa. 669 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 670 * @stable ICU 71 671 */ 672 static IncrementPrecision incrementExact(uint64_t mantissa, int16_t magnitude); 673 674 /** 675 * Show numbers rounded and padded according to the rules for the currency unit. The most common 676 * rounding precision settings for currencies include <code>Precision::fixedFraction(2)</code>, 677 * <code>Precision::integer()</code>, and <code>Precision::increment(0.05)</code> for cash transactions 678 * ("nickel rounding"). 679 * 680 * <p> 681 * The exact rounding details will be resolved at runtime based on the currency unit specified in the 682 * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another 683 * currency, the withCurrency() method can be called on the return value of this method. 684 * 685 * @param currencyUsage 686 * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may 687 * be limited by the available denominations of cash or coins). 688 * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter. 689 * @stable ICU 60 690 */ 691 static CurrencyPrecision currency(UCurrencyUsage currencyUsage); 692 693 /** 694 * Configure how trailing zeros are displayed on numbers. For example, to hide trailing zeros 695 * when the number is an integer, use UNUM_TRAILING_ZERO_HIDE_IF_WHOLE. 696 * 697 * @param trailingZeroDisplay Option to configure the display of trailing zeros. 698 * @stable ICU 69 699 */ 700 Precision trailingZeroDisplay(UNumberTrailingZeroDisplay trailingZeroDisplay) const; 701 702 private: 703 enum PrecisionType { 704 RND_BOGUS, 705 RND_NONE, 706 RND_FRACTION, 707 RND_SIGNIFICANT, 708 RND_FRACTION_SIGNIFICANT, 709 710 // Used for strange increments like 3.14. 711 RND_INCREMENT, 712 713 // Used for increments with 1 as the only digit. This is different than fraction 714 // rounding because it supports having additional trailing zeros. For example, this 715 // class is used to round with the increment 0.010. 716 RND_INCREMENT_ONE, 717 718 // Used for increments with 5 as the only digit (nickel rounding). 719 RND_INCREMENT_FIVE, 720 721 RND_CURRENCY, 722 RND_ERROR 723 } fType; 724 725 union PrecisionUnion { 726 /** @internal (private) */ 727 struct FractionSignificantSettings { 728 // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT 729 /** @internal (private) */ 730 impl::digits_t fMinFrac; 731 /** @internal (private) */ 732 impl::digits_t fMaxFrac; 733 /** @internal (private) */ 734 impl::digits_t fMinSig; 735 /** @internal (private) */ 736 impl::digits_t fMaxSig; 737 /** @internal (private) */ 738 UNumberRoundingPriority fPriority; 739 /** 740 * Whether to retain trailing zeros based on the looser strategy. 741 * @internal (private) 742 */ 743 bool fRetain; 744 } fracSig; 745 /** @internal (private) */ 746 struct IncrementSettings { 747 // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE 748 // Note: This is a union, so we shouldn't own memory, since 749 // the default destructor would leak it. 750 /** @internal (private) */ 751 uint64_t fIncrement; 752 /** @internal (private) */ 753 impl::digits_t fIncrementMagnitude; 754 /** @internal (private) */ 755 impl::digits_t fMinFrac; 756 } increment; 757 UCurrencyUsage currencyUsage; // For RND_CURRENCY 758 UErrorCode errorCode; // For RND_ERROR 759 } fUnion; 760 761 UNumberTrailingZeroDisplay fTrailingZeroDisplay = UNUM_TRAILING_ZERO_AUTO; 762 763 typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings; 764 typedef PrecisionUnion::IncrementSettings IncrementSettings; 765 Precision(const PrecisionType & type,const PrecisionUnion & union_)766 Precision(const PrecisionType& type, const PrecisionUnion& union_) 767 : fType(type), fUnion(union_) {} 768 Precision(UErrorCode errorCode)769 Precision(UErrorCode errorCode) : fType(RND_ERROR) { 770 fUnion.errorCode = errorCode; 771 } 772 Precision()773 Precision() : fType(RND_BOGUS) {} 774 isBogus()775 bool isBogus() const { 776 return fType == RND_BOGUS; 777 } 778 copyErrorTo(UErrorCode & status)779 UBool copyErrorTo(UErrorCode &status) const { 780 if (fType == RND_ERROR) { 781 status = fUnion.errorCode; 782 return true; 783 } 784 return false; 785 } 786 787 // On the parent type so that this method can be called internally on Precision instances. 788 Precision withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const; 789 790 static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac); 791 792 static Precision constructSignificant(int32_t minSig, int32_t maxSig); 793 794 static Precision constructFractionSignificant( 795 const FractionPrecision &base, 796 int32_t minSig, 797 int32_t maxSig, 798 UNumberRoundingPriority priority, 799 bool retain); 800 801 static IncrementPrecision constructIncrement(uint64_t increment, impl::digits_t magnitude); 802 803 static CurrencyPrecision constructCurrency(UCurrencyUsage usage); 804 805 // To allow MacroProps/MicroProps to initialize bogus instances: 806 friend struct impl::MacroProps; 807 friend struct impl::MicroProps; 808 809 // To allow NumberFormatterImpl to access isBogus() and other internal methods: 810 friend class impl::NumberFormatterImpl; 811 812 // To allow NumberPropertyMapper to create instances from DecimalFormatProperties: 813 friend class impl::NumberPropertyMapper; 814 815 // To allow access to the main implementation class: 816 friend class impl::RoundingImpl; 817 818 // To allow child classes to call private methods: 819 friend class FractionPrecision; 820 friend class CurrencyPrecision; 821 friend class IncrementPrecision; 822 823 // To allow access to the skeleton generation code: 824 friend class impl::GeneratorHelpers; 825 826 // To allow access to isBogus and the default (bogus) constructor: 827 friend class units::UnitsRouter; 828 }; 829 830 /** 831 * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be 832 * used when formatting numbers in NumberFormatter. 833 * 834 * <p> 835 * To create a FractionPrecision, use one of the factory methods on Precision. 836 * 837 * @stable ICU 60 838 */ 839 class U_I18N_API FractionPrecision : public Precision { 840 public: 841 /** 842 * Override maximum fraction digits with maximum significant digits depending on the magnitude 843 * of the number. See UNumberRoundingPriority. 844 * 845 * @param minSignificantDigits 846 * Pad trailing zeros to achieve this minimum number of significant digits. 847 * @param maxSignificantDigits 848 * Round the number to achieve this maximum number of significant digits. 849 * @param priority 850 * How to disambiguate between fraction digits and significant digits. 851 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 852 * 853 * @stable ICU 69 854 */ 855 Precision withSignificantDigits( 856 int32_t minSignificantDigits, 857 int32_t maxSignificantDigits, 858 UNumberRoundingPriority priority) const; 859 860 /** 861 * Ensure that no less than this number of significant digits are retained when rounding 862 * according to fraction rules. 863 * 864 * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum 865 * figures set to 2, 3.141 becomes "3.1" instead. 866 * 867 * This setting does not affect the number of trailing zeros. For example, 3.01 would print as 868 * "3", not "3.0". 869 * 870 * This is equivalent to `withSignificantDigits(1, minSignificantDigits, RELAXED)`. 871 * 872 * @param minSignificantDigits 873 * The number of significant figures to guarantee. 874 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 875 * @stable ICU 60 876 */ 877 Precision withMinDigits(int32_t minSignificantDigits) const; 878 879 /** 880 * Ensure that no more than this number of significant digits are retained when rounding 881 * according to fraction rules. 882 * 883 * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum 884 * figures set to 2, 123.4 becomes "120" instead. 885 * 886 * This setting does not affect the number of trailing zeros. For example, with fixed fraction 887 * of 2, 123.4 would become "120.00". 888 * 889 * This is equivalent to `withSignificantDigits(1, maxSignificantDigits, STRICT)`. 890 * 891 * @param maxSignificantDigits 892 * Round the number to no more than this number of significant figures. 893 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 894 * @stable ICU 60 895 */ 896 Precision withMaxDigits(int32_t maxSignificantDigits) const; 897 898 private: 899 // Inherit constructor 900 using Precision::Precision; 901 902 // To allow parent class to call this class's constructor: 903 friend class Precision; 904 }; 905 906 /** 907 * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in 908 * NumberFormatter. 909 * 910 * <p> 911 * To create a CurrencyPrecision, use one of the factory methods on Precision. 912 * 913 * @stable ICU 60 914 */ 915 class U_I18N_API CurrencyPrecision : public Precision { 916 public: 917 /** 918 * Associates a currency with this rounding precision. 919 * 920 * <p> 921 * <strong>Calling this method is <em>not required</em></strong>, because the currency specified in unit() 922 * is automatically applied to currency rounding precisions. However, 923 * this method enables you to override that automatic association. 924 * 925 * <p> 926 * This method also enables numbers to be formatted using currency rounding rules without explicitly using a 927 * currency format. 928 * 929 * @param currency 930 * The currency to associate with this rounding precision. 931 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 932 * @stable ICU 60 933 */ 934 Precision withCurrency(const CurrencyUnit ¤cy) const; 935 936 private: 937 // Inherit constructor 938 using Precision::Precision; 939 940 // To allow parent class to call this class's constructor: 941 friend class Precision; 942 }; 943 944 /** 945 * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in 946 * NumberFormatter. 947 * 948 * <p> 949 * To create an IncrementPrecision, use one of the factory methods on Precision. 950 * 951 * @stable ICU 60 952 */ 953 class U_I18N_API IncrementPrecision : public Precision { 954 public: 955 /** 956 * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if 957 * necessary. By default, no trailing zeros are added. 958 * 959 * <p> 960 * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00", 961 * "0.50", "1.00", and "1.50". 962 * 963 * <p> 964 * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment. 965 * 966 * @param minFrac The minimum number of digits after the decimal separator. 967 * @return A precision for chaining or passing to the NumberFormatter precision() setter. 968 * @stable ICU 60 969 */ 970 Precision withMinFraction(int32_t minFrac) const; 971 972 private: 973 // Inherit constructor 974 using Precision::Precision; 975 976 // To allow parent class to call this class's constructor: 977 friend class Precision; 978 }; 979 980 /** 981 * A class that defines the strategy for padding and truncating integers before the decimal separator. 982 * 983 * <p> 984 * To create an IntegerWidth, use one of the factory methods. 985 * 986 * @stable ICU 60 987 * @see NumberFormatter 988 */ 989 class U_I18N_API IntegerWidth : public UMemory { 990 public: 991 /** 992 * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator. 993 * 994 * <p> 995 * For example, with minInt=3, the number 55 will get printed as "055". 996 * 997 * @param minInt 998 * The minimum number of places before the decimal separator. 999 * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter. 1000 * @stable ICU 60 1001 */ 1002 static IntegerWidth zeroFillTo(int32_t minInt); 1003 1004 /** 1005 * Truncate numbers exceeding a certain number of numerals before the decimal separator. 1006 * 1007 * For example, with maxInt=3, the number 1234 will get printed as "234". 1008 * 1009 * @param maxInt 1010 * The maximum number of places before the decimal separator. maxInt == -1 means no 1011 * truncation. 1012 * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter. 1013 * @stable ICU 60 1014 */ 1015 IntegerWidth truncateAt(int32_t maxInt); 1016 1017 private: 1018 union { 1019 struct { 1020 impl::digits_t fMinInt; 1021 impl::digits_t fMaxInt; 1022 bool fFormatFailIfMoreThanMaxDigits; 1023 } minMaxInt; 1024 UErrorCode errorCode; 1025 } fUnion; 1026 bool fHasError = false; 1027 1028 IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits); 1029 IntegerWidth(UErrorCode errorCode)1030 IntegerWidth(UErrorCode errorCode) { // NOLINT 1031 fUnion.errorCode = errorCode; 1032 fHasError = true; 1033 } 1034 IntegerWidth()1035 IntegerWidth() { // NOLINT 1036 fUnion.minMaxInt.fMinInt = -1; 1037 } 1038 1039 /** Returns the default instance. */ standard()1040 static IntegerWidth standard() { 1041 return IntegerWidth::zeroFillTo(1); 1042 } 1043 isBogus()1044 bool isBogus() const { 1045 return !fHasError && fUnion.minMaxInt.fMinInt == -1; 1046 } 1047 copyErrorTo(UErrorCode & status)1048 UBool copyErrorTo(UErrorCode &status) const { 1049 if (fHasError) { 1050 status = fUnion.errorCode; 1051 return true; 1052 } 1053 return false; 1054 } 1055 1056 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const; 1057 1058 bool operator==(const IntegerWidth& other) const; 1059 1060 // To allow MacroProps/MicroProps to initialize empty instances: 1061 friend struct impl::MacroProps; 1062 friend struct impl::MicroProps; 1063 1064 // To allow NumberFormatterImpl to access isBogus(): 1065 friend class impl::NumberFormatterImpl; 1066 1067 // To allow the use of this class when formatting: 1068 friend class impl::MutablePatternModifier; 1069 friend class impl::ImmutablePatternModifier; 1070 1071 // So that NumberPropertyMapper can create instances 1072 friend class impl::NumberPropertyMapper; 1073 1074 // To allow access to the skeleton generation code: 1075 friend class impl::GeneratorHelpers; 1076 }; 1077 1078 /** 1079 * A class that defines a quantity by which a number should be multiplied when formatting. 1080 * 1081 * <p> 1082 * To create a Scale, use one of the factory methods. 1083 * 1084 * @stable ICU 62 1085 */ 1086 class U_I18N_API Scale : public UMemory { 1087 public: 1088 /** 1089 * Do not change the value of numbers when formatting or parsing. 1090 * 1091 * @return A Scale to prevent any multiplication. 1092 * @stable ICU 62 1093 */ 1094 static Scale none(); 1095 1096 /** 1097 * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit: 1098 * 1099 * <pre> 1100 * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2)) 1101 * </pre> 1102 * 1103 * @return A Scale for passing to the setter in NumberFormatter. 1104 * @stable ICU 62 1105 */ 1106 static Scale powerOfTen(int32_t power); 1107 1108 /** 1109 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions. 1110 * 1111 * This method takes a string in a decimal number format with syntax 1112 * as defined in the Decimal Arithmetic Specification, available at 1113 * http://speleotrove.com/decimal 1114 * 1115 * Also see the version of this method that takes a double. 1116 * 1117 * @return A Scale for passing to the setter in NumberFormatter. 1118 * @stable ICU 62 1119 */ 1120 static Scale byDecimal(StringPiece multiplicand); 1121 1122 /** 1123 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions. 1124 * 1125 * This method takes a double; also see the version of this method that takes an exact decimal. 1126 * 1127 * @return A Scale for passing to the setter in NumberFormatter. 1128 * @stable ICU 62 1129 */ 1130 static Scale byDouble(double multiplicand); 1131 1132 /** 1133 * Multiply a number by both a power of ten and by an arbitrary double value. 1134 * 1135 * @return A Scale for passing to the setter in NumberFormatter. 1136 * @stable ICU 62 1137 */ 1138 static Scale byDoubleAndPowerOfTen(double multiplicand, int32_t power); 1139 1140 // We need a custom destructor for the DecNum, which means we need to declare 1141 // the copy/move constructor/assignment quartet. 1142 1143 /** @stable ICU 62 */ 1144 Scale(const Scale& other); 1145 1146 /** @stable ICU 62 */ 1147 Scale& operator=(const Scale& other); 1148 1149 /** @stable ICU 62 */ 1150 Scale(Scale&& src) noexcept; 1151 1152 /** @stable ICU 62 */ 1153 Scale& operator=(Scale&& src) noexcept; 1154 1155 /** @stable ICU 62 */ 1156 ~Scale(); 1157 1158 #ifndef U_HIDE_INTERNAL_API 1159 /** @internal */ 1160 Scale(int32_t magnitude, impl::DecNum* arbitraryToAdopt); 1161 #endif /* U_HIDE_INTERNAL_API */ 1162 1163 private: 1164 int32_t fMagnitude; 1165 impl::DecNum* fArbitrary; 1166 UErrorCode fError; 1167 Scale(UErrorCode error)1168 Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {} 1169 Scale()1170 Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {} 1171 isValid()1172 bool isValid() const { 1173 return fMagnitude != 0 || fArbitrary != nullptr; 1174 } 1175 copyErrorTo(UErrorCode & status)1176 UBool copyErrorTo(UErrorCode &status) const { 1177 if (U_FAILURE(fError)) { 1178 status = fError; 1179 return true; 1180 } 1181 return false; 1182 } 1183 1184 void applyTo(impl::DecimalQuantity& quantity) const; 1185 1186 void applyReciprocalTo(impl::DecimalQuantity& quantity) const; 1187 1188 // To allow MacroProps/MicroProps to initialize empty instances: 1189 friend struct impl::MacroProps; 1190 friend struct impl::MicroProps; 1191 1192 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1193 friend class impl::NumberFormatterImpl; 1194 1195 // To allow the helper class MultiplierFormatHandler access to private fields: 1196 friend class impl::MultiplierFormatHandler; 1197 1198 // To allow access to the skeleton generation code: 1199 friend class impl::GeneratorHelpers; 1200 1201 // To allow access to parsing code: 1202 friend class ::icu::numparse::impl::NumberParserImpl; 1203 friend class ::icu::numparse::impl::MultiplierParseHandler; 1204 }; 1205 1206 namespace impl { 1207 1208 // Do not enclose entire StringProp with #ifndef U_HIDE_INTERNAL_API, needed for a protected field. 1209 // And do not enclose its class boilerplate within #ifndef U_HIDE_INTERNAL_API. 1210 /** 1211 * Manages NumberFormatterSettings::usage()'s char* instance on the heap. 1212 * @internal 1213 */ 1214 class U_I18N_API StringProp : public UMemory { 1215 1216 public: 1217 /** @internal */ 1218 ~StringProp(); 1219 1220 /** @internal */ 1221 StringProp(const StringProp &other); 1222 1223 /** @internal */ 1224 StringProp &operator=(const StringProp &other); 1225 1226 #ifndef U_HIDE_INTERNAL_API 1227 1228 /** @internal */ 1229 StringProp(StringProp &&src) noexcept; 1230 1231 /** @internal */ 1232 StringProp &operator=(StringProp &&src) noexcept; 1233 1234 /** @internal */ length()1235 int16_t length() const { 1236 return fLength; 1237 } 1238 1239 /** @internal 1240 * Makes a copy of value. Set to "" to unset. 1241 */ 1242 void set(StringPiece value); 1243 1244 /** @internal */ isSet()1245 bool isSet() const { 1246 return fLength > 0; 1247 } 1248 1249 #endif // U_HIDE_INTERNAL_API 1250 1251 private: 1252 char *fValue; 1253 int16_t fLength; 1254 UErrorCode fError; 1255 StringProp()1256 StringProp() : fValue(nullptr), fLength(0), fError(U_ZERO_ERROR) { 1257 } 1258 1259 /** @internal (private) */ copyErrorTo(UErrorCode & status)1260 UBool copyErrorTo(UErrorCode &status) const { 1261 if (U_FAILURE(fError)) { 1262 status = fError; 1263 return true; 1264 } 1265 return false; 1266 } 1267 1268 // Allow NumberFormatterImpl to access fValue. 1269 friend class impl::NumberFormatterImpl; 1270 1271 // Allow skeleton generation code to access private members. 1272 friend class impl::GeneratorHelpers; 1273 1274 // Allow MacroProps/MicroProps to initialize empty instances and to call 1275 // copyErrorTo(). 1276 friend struct impl::MacroProps; 1277 }; 1278 1279 // Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field 1280 /** @internal */ 1281 class U_I18N_API SymbolsWrapper : public UMemory { 1282 public: 1283 /** @internal */ SymbolsWrapper()1284 SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {} 1285 1286 /** @internal */ 1287 SymbolsWrapper(const SymbolsWrapper &other); 1288 1289 /** @internal */ 1290 SymbolsWrapper &operator=(const SymbolsWrapper &other); 1291 1292 /** @internal */ 1293 SymbolsWrapper(SymbolsWrapper&& src) noexcept; 1294 1295 /** @internal */ 1296 SymbolsWrapper &operator=(SymbolsWrapper&& src) noexcept; 1297 1298 /** @internal */ 1299 ~SymbolsWrapper(); 1300 1301 #ifndef U_HIDE_INTERNAL_API 1302 1303 /** 1304 * The provided object is copied, but we do not adopt it. 1305 * @internal 1306 */ 1307 void setTo(const DecimalFormatSymbols &dfs); 1308 1309 /** 1310 * Adopt the provided object. 1311 * @internal 1312 */ 1313 void setTo(const NumberingSystem *ns); 1314 1315 /** 1316 * Whether the object is currently holding a DecimalFormatSymbols. 1317 * @internal 1318 */ 1319 bool isDecimalFormatSymbols() const; 1320 1321 /** 1322 * Whether the object is currently holding a NumberingSystem. 1323 * @internal 1324 */ 1325 bool isNumberingSystem() const; 1326 1327 /** 1328 * Get the DecimalFormatSymbols pointer. No ownership change. 1329 * @internal 1330 */ 1331 const DecimalFormatSymbols *getDecimalFormatSymbols() const; 1332 1333 /** 1334 * Get the NumberingSystem pointer. No ownership change. 1335 * @internal 1336 */ 1337 const NumberingSystem *getNumberingSystem() const; 1338 1339 #endif // U_HIDE_INTERNAL_API 1340 1341 /** @internal */ copyErrorTo(UErrorCode & status)1342 UBool copyErrorTo(UErrorCode &status) const { 1343 if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) { 1344 status = U_MEMORY_ALLOCATION_ERROR; 1345 return true; 1346 } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) { 1347 status = U_MEMORY_ALLOCATION_ERROR; 1348 return true; 1349 } 1350 return false; 1351 } 1352 1353 private: 1354 enum SymbolsPointerType { 1355 SYMPTR_NONE, SYMPTR_DFS, SYMPTR_NS 1356 } fType; 1357 1358 union { 1359 const DecimalFormatSymbols *dfs; 1360 const NumberingSystem *ns; 1361 } fPtr; 1362 1363 void doCopyFrom(const SymbolsWrapper &other); 1364 1365 void doMoveFrom(SymbolsWrapper&& src); 1366 1367 void doCleanup(); 1368 }; 1369 1370 // Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field 1371 /** @internal */ 1372 class U_I18N_API Grouper : public UMemory { 1373 public: 1374 #ifndef U_HIDE_INTERNAL_API 1375 /** @internal */ 1376 static Grouper forStrategy(UNumberGroupingStrategy grouping); 1377 1378 /** 1379 * Resolve the values in Properties to a Grouper object. 1380 * @internal 1381 */ 1382 static Grouper forProperties(const DecimalFormatProperties& properties); 1383 1384 // Future: static Grouper forProperties(DecimalFormatProperties& properties); 1385 1386 /** @internal */ Grouper(int16_t grouping1,int16_t grouping2,int16_t minGrouping,UNumberGroupingStrategy strategy)1387 Grouper(int16_t grouping1, int16_t grouping2, int16_t minGrouping, UNumberGroupingStrategy strategy) 1388 : fGrouping1(grouping1), 1389 fGrouping2(grouping2), 1390 fMinGrouping(minGrouping), 1391 fStrategy(strategy) {} 1392 1393 /** @internal */ 1394 int16_t getPrimary() const; 1395 1396 /** @internal */ 1397 int16_t getSecondary() const; 1398 #endif // U_HIDE_INTERNAL_API 1399 1400 private: 1401 /** 1402 * The grouping sizes, with the following special values: 1403 * <ul> 1404 * <li>-1 = no grouping 1405 * <li>-2 = needs locale data 1406 * <li>-4 = fall back to Western grouping if not in locale 1407 * </ul> 1408 */ 1409 int16_t fGrouping1; 1410 int16_t fGrouping2; 1411 1412 /** 1413 * The minimum grouping size, with the following special values: 1414 * <ul> 1415 * <li>-2 = needs locale data 1416 * <li>-3 = no less than 2 1417 * </ul> 1418 */ 1419 int16_t fMinGrouping; 1420 1421 /** 1422 * The UNumberGroupingStrategy that was used to create this Grouper, or UNUM_GROUPING_COUNT if this 1423 * was not created from a UNumberGroupingStrategy. 1424 */ 1425 UNumberGroupingStrategy fStrategy; 1426 Grouper()1427 Grouper() : fGrouping1(-3) {} 1428 isBogus()1429 bool isBogus() const { 1430 return fGrouping1 == -3; 1431 } 1432 1433 /** NON-CONST: mutates the current instance. */ 1434 void setLocaleData(const impl::ParsedPatternInfo &patternInfo, const Locale& locale); 1435 1436 bool groupAtPosition(int32_t position, const impl::DecimalQuantity &value) const; 1437 1438 // To allow MacroProps/MicroProps to initialize empty instances: 1439 friend struct MacroProps; 1440 friend struct MicroProps; 1441 friend struct SimpleMicroProps; 1442 1443 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1444 friend class NumberFormatterImpl; 1445 friend class ::icu::number::SimpleNumberFormatter; 1446 1447 // To allow NumberParserImpl to perform setLocaleData(): 1448 friend class ::icu::numparse::impl::NumberParserImpl; 1449 1450 // To allow access to the skeleton generation code: 1451 friend class impl::GeneratorHelpers; 1452 }; 1453 1454 // Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field 1455 /** @internal */ 1456 class U_I18N_API Padder : public UMemory { 1457 public: 1458 #ifndef U_HIDE_INTERNAL_API 1459 /** @internal */ 1460 static Padder none(); 1461 1462 /** @internal */ 1463 static Padder codePoints(UChar32 cp, int32_t targetWidth, UNumberFormatPadPosition position); 1464 1465 /** @internal */ 1466 static Padder forProperties(const DecimalFormatProperties& properties); 1467 #endif // U_HIDE_INTERNAL_API 1468 1469 private: 1470 UChar32 fWidth; // -3 = error; -2 = bogus; -1 = no padding 1471 union { 1472 struct { 1473 int32_t fCp; 1474 UNumberFormatPadPosition fPosition; 1475 } padding; 1476 UErrorCode errorCode; 1477 } fUnion; 1478 1479 Padder(UChar32 cp, int32_t width, UNumberFormatPadPosition position); 1480 1481 Padder(int32_t width); 1482 Padder(UErrorCode errorCode)1483 Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT 1484 fUnion.errorCode = errorCode; 1485 } 1486 Padder()1487 Padder() : fWidth(-2) {} // NOLINT 1488 isBogus()1489 bool isBogus() const { 1490 return fWidth == -2; 1491 } 1492 copyErrorTo(UErrorCode & status)1493 UBool copyErrorTo(UErrorCode &status) const { 1494 if (fWidth == -3) { 1495 status = fUnion.errorCode; 1496 return true; 1497 } 1498 return false; 1499 } 1500 isValid()1501 bool isValid() const { 1502 return fWidth > 0; 1503 } 1504 1505 int32_t padAndApply(const impl::Modifier &mod1, const impl::Modifier &mod2, 1506 FormattedStringBuilder &string, int32_t leftIndex, int32_t rightIndex, 1507 UErrorCode &status) const; 1508 1509 // To allow MacroProps/MicroProps to initialize empty instances: 1510 friend struct MacroProps; 1511 friend struct MicroProps; 1512 1513 // To allow NumberFormatterImpl to access isBogus() and perform other operations: 1514 friend class impl::NumberFormatterImpl; 1515 1516 // To allow access to the skeleton generation code: 1517 friend class impl::GeneratorHelpers; 1518 }; 1519 1520 // Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field 1521 /** @internal */ 1522 struct U_I18N_API MacroProps : public UMemory { 1523 /** @internal */ 1524 Notation notation; 1525 1526 /** @internal */ 1527 MeasureUnit unit; // = MeasureUnit(); (the base dimensionless unit) 1528 1529 /** @internal */ 1530 MeasureUnit perUnit; // = MeasureUnit(); (the base dimensionless unit) 1531 1532 /** @internal */ 1533 Precision precision; // = Precision(); (bogus) 1534 1535 /** @internal */ 1536 UNumberFormatRoundingMode roundingMode = UNUM_ROUND_HALFEVEN; 1537 1538 /** @internal */ 1539 Grouper grouper; // = Grouper(); (bogus) 1540 1541 /** @internal */ 1542 Padder padder; // = Padder(); (bogus) 1543 1544 /** @internal */ 1545 IntegerWidth integerWidth; // = IntegerWidth(); (bogus) 1546 1547 /** @internal */ 1548 SymbolsWrapper symbols; 1549 1550 // UNUM_XYZ_COUNT denotes null (bogus) values. 1551 1552 /** @internal */ 1553 UNumberUnitWidth unitWidth = UNUM_UNIT_WIDTH_COUNT; 1554 1555 /** @internal */ 1556 UNumberSignDisplay sign = UNUM_SIGN_COUNT; 1557 1558 /** @internal */ 1559 bool approximately = false; 1560 1561 /** @internal */ 1562 UNumberDecimalSeparatorDisplay decimal = UNUM_DECIMAL_SEPARATOR_COUNT; 1563 1564 /** @internal */ 1565 Scale scale; // = Scale(); (benign value) 1566 1567 /** @internal */ 1568 StringProp usage; // = StringProp(); (no usage) 1569 1570 /** @internal */ 1571 StringProp unitDisplayCase; // = StringProp(); (nominative) 1572 1573 /** @internal */ 1574 const AffixPatternProvider* affixProvider = nullptr; // no ownership 1575 1576 /** @internal */ 1577 const PluralRules* rules = nullptr; // no ownership 1578 1579 /** @internal */ 1580 int32_t threshold = kInternalDefaultThreshold; 1581 1582 /** @internal */ 1583 Locale locale; 1584 1585 // NOTE: Uses default copy and move constructors. 1586 1587 /** 1588 * Check all members for errors. 1589 * @internal 1590 */ copyErrorToMacroProps1591 bool copyErrorTo(UErrorCode &status) const { 1592 return notation.copyErrorTo(status) || precision.copyErrorTo(status) || 1593 padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) || 1594 symbols.copyErrorTo(status) || scale.copyErrorTo(status) || usage.copyErrorTo(status) || 1595 unitDisplayCase.copyErrorTo(status); 1596 } 1597 }; 1598 1599 } // namespace impl 1600 1601 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) 1602 // Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method 1603 // is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation 1604 // inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is 1605 // fully defined. However, since each translation unit explicitly instantiates all the necessary template classes, 1606 // they will all be passed to the linker, and the linker will still find and export all the class members. 1607 #pragma warning(push) 1608 #pragma warning(disable: 4661) 1609 #endif 1610 1611 /** 1612 * An abstract base class for specifying settings related to number formatting. This class is implemented by 1613 * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. This class is not intended for 1614 * public subclassing. 1615 */ 1616 template<typename Derived> 1617 class U_I18N_API NumberFormatterSettings { 1618 public: 1619 /** 1620 * Specifies the notation style (simple, scientific, or compact) for rendering numbers. 1621 * 1622 * <ul> 1623 * <li>Simple notation: "12,300" 1624 * <li>Scientific notation: "1.23E4" 1625 * <li>Compact notation: "12K" 1626 * </ul> 1627 * 1628 * <p> 1629 * All notation styles will be properly localized with locale data, and all notation styles are compatible with 1630 * units, rounding precisions, and other number formatter settings. 1631 * 1632 * <p> 1633 * Pass this method the return value of a {@link Notation} factory method. For example: 1634 * 1635 * <pre> 1636 * NumberFormatter::with().notation(Notation::compactShort()) 1637 * </pre> 1638 * 1639 * The default is to use simple notation. 1640 * 1641 * @param notation 1642 * The notation strategy to use. 1643 * @return The fluent chain. 1644 * @see Notation 1645 * @stable ICU 60 1646 */ 1647 Derived notation(const Notation ¬ation) const &; 1648 1649 /** 1650 * Overload of notation() for use on an rvalue reference. 1651 * 1652 * @param notation 1653 * The notation strategy to use. 1654 * @return The fluent chain. 1655 * @see #notation 1656 * @stable ICU 62 1657 */ 1658 Derived notation(const Notation ¬ation) &&; 1659 1660 /** 1661 * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers. 1662 * 1663 * <ul> 1664 * <li>Unit of measure: "12.3 meters" 1665 * <li>Currency: "$12.30" 1666 * <li>Percent: "12.3%" 1667 * </ul> 1668 * 1669 * All units will be properly localized with locale data, and all units are compatible with notation styles, 1670 * rounding precisions, and other number formatter settings. 1671 * 1672 * \note If the usage() is set, the output unit **will be changed** to 1673 * produce localised units, according to usage, locale and unit. See 1674 * FormattedNumber::getOutputUnit(). 1675 * 1676 * Pass this method any instance of {@link MeasureUnit}. For units of measure: 1677 * 1678 * <pre> 1679 * NumberFormatter::with().unit(MeasureUnit::getMeter()) 1680 * NumberFormatter::with().unit(MeasureUnit::forIdentifier("foot-per-second", status)) 1681 * </pre> 1682 * 1683 * Currency: 1684 * 1685 * <pre> 1686 * NumberFormatter::with().unit(CurrencyUnit(u"USD", status)) 1687 * </pre> 1688 * 1689 * Percent: 1690 * 1691 * <pre> 1692 * NumberFormatter::with().unit(NoUnit.percent()) 1693 * </pre> 1694 * 1695 * See {@link #perUnit} for information on how to format strings like "5 meters per second". 1696 * 1697 * The default is to render without units (equivalent to NoUnit.base()). 1698 * 1699 * @param unit 1700 * The unit to render. 1701 * @return The fluent chain. 1702 * @see MeasureUnit 1703 * @see Currency 1704 * @see NoUnit 1705 * @see #perUnit 1706 * @stable ICU 60 1707 */ 1708 Derived unit(const icu::MeasureUnit &unit) const &; 1709 1710 /** 1711 * Overload of unit() for use on an rvalue reference. 1712 * 1713 * @param unit 1714 * The unit to render. 1715 * @return The fluent chain. 1716 * @see #unit 1717 * @stable ICU 62 1718 */ 1719 Derived unit(const icu::MeasureUnit &unit) &&; 1720 1721 /** 1722 * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory 1723 * methods that return pointers that need ownership. 1724 * 1725 * Note: consider using the MeasureFormat factory methods that return by value. 1726 * 1727 * @param unit 1728 * The unit to render. 1729 * @return The fluent chain. 1730 * @see #unit 1731 * @see MeasureUnit 1732 * @stable ICU 60 1733 */ 1734 Derived adoptUnit(icu::MeasureUnit *unit) const &; 1735 1736 /** 1737 * Overload of adoptUnit() for use on an rvalue reference. 1738 * 1739 * @param unit 1740 * The unit to render. 1741 * @return The fluent chain. 1742 * @see #adoptUnit 1743 * @stable ICU 62 1744 */ 1745 Derived adoptUnit(icu::MeasureUnit *unit) &&; 1746 1747 /** 1748 * Sets a unit to be used in the denominator. For example, to format "3 m/s", pass METER to the unit and SECOND to 1749 * the perUnit. 1750 * 1751 * Pass this method any instance of {@link MeasureUnit}. Example: 1752 * 1753 * <pre> 1754 * NumberFormatter::with() 1755 * .unit(MeasureUnit::getMeter()) 1756 * .perUnit(MeasureUnit::getSecond()) 1757 * </pre> 1758 * 1759 * The default is not to display any unit in the denominator. 1760 * 1761 * If a per-unit is specified without a primary unit via {@link #unit}, the behavior is undefined. 1762 * 1763 * @param perUnit 1764 * The unit to render in the denominator. 1765 * @return The fluent chain 1766 * @see #unit 1767 * @stable ICU 61 1768 */ 1769 Derived perUnit(const icu::MeasureUnit &perUnit) const &; 1770 1771 /** 1772 * Overload of perUnit() for use on an rvalue reference. 1773 * 1774 * @param perUnit 1775 * The unit to render in the denominator. 1776 * @return The fluent chain. 1777 * @see #perUnit 1778 * @stable ICU 62 1779 */ 1780 Derived perUnit(const icu::MeasureUnit &perUnit) &&; 1781 1782 /** 1783 * Like perUnit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory 1784 * methods that return pointers that need ownership. 1785 * 1786 * Note: consider using the MeasureFormat factory methods that return by value. 1787 * 1788 * @param perUnit 1789 * The unit to render in the denominator. 1790 * @return The fluent chain. 1791 * @see #perUnit 1792 * @see MeasureUnit 1793 * @stable ICU 61 1794 */ 1795 Derived adoptPerUnit(icu::MeasureUnit *perUnit) const &; 1796 1797 /** 1798 * Overload of adoptPerUnit() for use on an rvalue reference. 1799 * 1800 * @param perUnit 1801 * The unit to render in the denominator. 1802 * @return The fluent chain. 1803 * @see #adoptPerUnit 1804 * @stable ICU 62 1805 */ 1806 Derived adoptPerUnit(icu::MeasureUnit *perUnit) &&; 1807 1808 /** 1809 * Specifies the rounding precision to use when formatting numbers. 1810 * 1811 * <ul> 1812 * <li>Round to 3 decimal places: "3.142" 1813 * <li>Round to 3 significant figures: "3.14" 1814 * <li>Round to the closest nickel: "3.15" 1815 * <li>Do not perform rounding: "3.1415926..." 1816 * </ul> 1817 * 1818 * <p> 1819 * Pass this method the return value of one of the factory methods on {@link Precision}. For example: 1820 * 1821 * <pre> 1822 * NumberFormatter::with().precision(Precision::fixedFraction(2)) 1823 * </pre> 1824 * 1825 * <p> 1826 * In most cases, the default rounding strategy is to round to 6 fraction places; i.e., 1827 * <code>Precision.maxFraction(6)</code>. The exceptions are if compact notation is being used, then the compact 1828 * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency, 1829 * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for 1830 * details). 1831 * 1832 * @param precision 1833 * The rounding precision to use. 1834 * @return The fluent chain. 1835 * @see Precision 1836 * @stable ICU 62 1837 */ 1838 Derived precision(const Precision& precision) const &; 1839 1840 /** 1841 * Overload of precision() for use on an rvalue reference. 1842 * 1843 * @param precision 1844 * The rounding precision to use. 1845 * @return The fluent chain. 1846 * @see #precision 1847 * @stable ICU 62 1848 */ 1849 Derived precision(const Precision& precision) &&; 1850 1851 /** 1852 * Specifies how to determine the direction to round a number when it has more digits than fit in the 1853 * desired precision. When formatting 1.235: 1854 * 1855 * <ul> 1856 * <li>Ceiling rounding mode with integer precision: "2" 1857 * <li>Half-down rounding mode with 2 fixed fraction digits: "1.23" 1858 * <li>Half-up rounding mode with 2 fixed fraction digits: "1.24" 1859 * </ul> 1860 * 1861 * The default is HALF_EVEN. For more information on rounding mode, see the ICU userguide here: 1862 * 1863 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes 1864 * 1865 * @param roundingMode The rounding mode to use. 1866 * @return The fluent chain. 1867 * @stable ICU 62 1868 */ 1869 Derived roundingMode(UNumberFormatRoundingMode roundingMode) const &; 1870 1871 /** 1872 * Overload of roundingMode() for use on an rvalue reference. 1873 * 1874 * @param roundingMode The rounding mode to use. 1875 * @return The fluent chain. 1876 * @see #roundingMode 1877 * @stable ICU 62 1878 */ 1879 Derived roundingMode(UNumberFormatRoundingMode roundingMode) &&; 1880 1881 /** 1882 * Specifies the grouping strategy to use when formatting numbers. 1883 * 1884 * <ul> 1885 * <li>Default grouping: "12,300" and "1,230" 1886 * <li>Grouping with at least 2 digits: "12,300" and "1230" 1887 * <li>No grouping: "12300" and "1230" 1888 * </ul> 1889 * 1890 * <p> 1891 * The exact grouping widths will be chosen based on the locale. 1892 * 1893 * <p> 1894 * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example: 1895 * 1896 * <pre> 1897 * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2) 1898 * </pre> 1899 * 1900 * The default is to perform grouping according to locale data; most locales, but not all locales, 1901 * enable it by default. 1902 * 1903 * @param strategy 1904 * The grouping strategy to use. 1905 * @return The fluent chain. 1906 * @stable ICU 61 1907 */ 1908 Derived grouping(UNumberGroupingStrategy strategy) const &; 1909 1910 /** 1911 * Overload of grouping() for use on an rvalue reference. 1912 * 1913 * @param strategy 1914 * The grouping strategy to use. 1915 * @return The fluent chain. 1916 * @see #grouping 1917 * @stable ICU 62 1918 */ 1919 Derived grouping(UNumberGroupingStrategy strategy) &&; 1920 1921 /** 1922 * Specifies the minimum and maximum number of digits to render before the decimal mark. 1923 * 1924 * <ul> 1925 * <li>Zero minimum integer digits: ".08" 1926 * <li>One minimum integer digit: "0.08" 1927 * <li>Two minimum integer digits: "00.08" 1928 * </ul> 1929 * 1930 * <p> 1931 * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example: 1932 * 1933 * <pre> 1934 * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2)) 1935 * </pre> 1936 * 1937 * The default is to have one minimum integer digit. 1938 * 1939 * @param style 1940 * The integer width to use. 1941 * @return The fluent chain. 1942 * @see IntegerWidth 1943 * @stable ICU 60 1944 */ 1945 Derived integerWidth(const IntegerWidth &style) const &; 1946 1947 /** 1948 * Overload of integerWidth() for use on an rvalue reference. 1949 * 1950 * @param style 1951 * The integer width to use. 1952 * @return The fluent chain. 1953 * @see #integerWidth 1954 * @stable ICU 62 1955 */ 1956 Derived integerWidth(const IntegerWidth &style) &&; 1957 1958 /** 1959 * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering 1960 * numbers. 1961 * 1962 * <ul> 1963 * <li><em>en_US</em> symbols: "12,345.67" 1964 * <li><em>fr_FR</em> symbols: "12 345,67" 1965 * <li><em>de_CH</em> symbols: "12’345.67" 1966 * <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇" 1967 * </ul> 1968 * 1969 * <p> 1970 * Pass this method an instance of {@link DecimalFormatSymbols}. For example: 1971 * 1972 * <pre> 1973 * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status)) 1974 * </pre> 1975 * 1976 * <p> 1977 * <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale. 1978 * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar 1979 * numbering system. 1980 * 1981 * <p> 1982 * <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object 1983 * after passing it into the fluent chain will not be seen. 1984 * 1985 * <p> 1986 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols 1987 * or NumberingSystem. 1988 * 1989 * <p> 1990 * The default is to choose the symbols based on the locale specified in the fluent chain. 1991 * 1992 * @param symbols 1993 * The DecimalFormatSymbols to use. 1994 * @return The fluent chain. 1995 * @see DecimalFormatSymbols 1996 * @stable ICU 60 1997 */ 1998 Derived symbols(const DecimalFormatSymbols &symbols) const &; 1999 2000 /** 2001 * Overload of symbols() for use on an rvalue reference. 2002 * 2003 * @param symbols 2004 * The DecimalFormatSymbols to use. 2005 * @return The fluent chain. 2006 * @see #symbols 2007 * @stable ICU 62 2008 */ 2009 Derived symbols(const DecimalFormatSymbols &symbols) &&; 2010 2011 /** 2012 * Specifies that the given numbering system should be used when fetching symbols. 2013 * 2014 * <ul> 2015 * <li>Latin numbering system: "12,345" 2016 * <li>Myanmar numbering system: "၁၂,၃၄၅" 2017 * <li>Math Sans Bold numbering system: "," 2018 * </ul> 2019 * 2020 * <p> 2021 * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin 2022 * alphabet numbering system (ASCII digits): 2023 * 2024 * <pre> 2025 * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status)) 2026 * </pre> 2027 * 2028 * <p> 2029 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols 2030 * or NumberingSystem. 2031 * 2032 * <p> 2033 * The default is to choose the best numbering system for the locale. 2034 * 2035 * <p> 2036 * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods. 2037 * 2038 * @param symbols 2039 * The NumberingSystem to use. 2040 * @return The fluent chain. 2041 * @see NumberingSystem 2042 * @stable ICU 60 2043 */ 2044 Derived adoptSymbols(NumberingSystem *symbols) const &; 2045 2046 /** 2047 * Overload of adoptSymbols() for use on an rvalue reference. 2048 * 2049 * @param symbols 2050 * The NumberingSystem to use. 2051 * @return The fluent chain. 2052 * @see #adoptSymbols 2053 * @stable ICU 62 2054 */ 2055 Derived adoptSymbols(NumberingSystem *symbols) &&; 2056 2057 /** 2058 * Sets the width of the unit (measure unit or currency). Most common values: 2059 * 2060 * <ul> 2061 * <li>Short: "$12.00", "12 m" 2062 * <li>ISO Code: "USD 12.00" 2063 * <li>Full name: "12.00 US dollars", "12 meters" 2064 * </ul> 2065 * 2066 * <p> 2067 * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example: 2068 * 2069 * <pre> 2070 * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME) 2071 * </pre> 2072 * 2073 * <p> 2074 * The default is the SHORT width. 2075 * 2076 * @param width 2077 * The width to use when rendering numbers. 2078 * @return The fluent chain 2079 * @see UNumberUnitWidth 2080 * @stable ICU 60 2081 */ 2082 Derived unitWidth(UNumberUnitWidth width) const &; 2083 2084 /** 2085 * Overload of unitWidth() for use on an rvalue reference. 2086 * 2087 * @param width 2088 * The width to use when rendering numbers. 2089 * @return The fluent chain. 2090 * @see #unitWidth 2091 * @stable ICU 62 2092 */ 2093 Derived unitWidth(UNumberUnitWidth width) &&; 2094 2095 /** 2096 * Sets the plus/minus sign display strategy. Most common values: 2097 * 2098 * <ul> 2099 * <li>Auto: "123", "-123" 2100 * <li>Always: "+123", "-123" 2101 * <li>Accounting: "$123", "($123)" 2102 * </ul> 2103 * 2104 * <p> 2105 * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example: 2106 * 2107 * <pre> 2108 * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) 2109 * </pre> 2110 * 2111 * <p> 2112 * The default is AUTO sign display. 2113 * 2114 * @param style 2115 * The sign display strategy to use when rendering numbers. 2116 * @return The fluent chain 2117 * @see UNumberSignDisplay 2118 * @stable ICU 60 2119 */ 2120 Derived sign(UNumberSignDisplay style) const &; 2121 2122 /** 2123 * Overload of sign() for use on an rvalue reference. 2124 * 2125 * @param style 2126 * The sign display strategy to use when rendering numbers. 2127 * @return The fluent chain. 2128 * @see #sign 2129 * @stable ICU 62 2130 */ 2131 Derived sign(UNumberSignDisplay style) &&; 2132 2133 /** 2134 * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common 2135 * values: 2136 * 2137 * <ul> 2138 * <li>Auto: "1" 2139 * <li>Always: "1." 2140 * </ul> 2141 * 2142 * <p> 2143 * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example: 2144 * 2145 * <pre> 2146 * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS) 2147 * </pre> 2148 * 2149 * <p> 2150 * The default is AUTO decimal separator display. 2151 * 2152 * @param style 2153 * The decimal separator display strategy to use when rendering numbers. 2154 * @return The fluent chain 2155 * @see UNumberDecimalSeparatorDisplay 2156 * @stable ICU 60 2157 */ 2158 Derived decimal(UNumberDecimalSeparatorDisplay style) const &; 2159 2160 /** 2161 * Overload of decimal() for use on an rvalue reference. 2162 * 2163 * @param style 2164 * The decimal separator display strategy to use when rendering numbers. 2165 * @return The fluent chain. 2166 * @see #decimal 2167 * @stable ICU 62 2168 */ 2169 Derived decimal(UNumberDecimalSeparatorDisplay style) &&; 2170 2171 /** 2172 * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting. 2173 * Most common values: 2174 * 2175 * <ul> 2176 * <li>Multiply by 100: useful for percentages. 2177 * <li>Multiply by an arbitrary value: useful for unit conversions. 2178 * </ul> 2179 * 2180 * <p> 2181 * Pass an element from a {@link Scale} factory method to this setter. For example: 2182 * 2183 * <pre> 2184 * NumberFormatter::with().scale(Scale::powerOfTen(2)) 2185 * </pre> 2186 * 2187 * <p> 2188 * The default is to not apply any multiplier. 2189 * 2190 * @param scale 2191 * The scale to apply when rendering numbers. 2192 * @return The fluent chain 2193 * @stable ICU 62 2194 */ 2195 Derived scale(const Scale &scale) const &; 2196 2197 /** 2198 * Overload of scale() for use on an rvalue reference. 2199 * 2200 * @param scale 2201 * The scale to apply when rendering numbers. 2202 * @return The fluent chain. 2203 * @see #scale 2204 * @stable ICU 62 2205 */ 2206 Derived scale(const Scale &scale) &&; 2207 2208 /** 2209 * Specifies the usage for which numbers will be formatted ("person-height", 2210 * "road", "rainfall", etc.) 2211 * 2212 * When a `usage` is specified, the output unit will change depending on the 2213 * `Locale` and the unit quantity. For example, formatting length 2214 * measurements specified in meters: 2215 * 2216 * `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")` 2217 * * When formatting 0.25, the output will be "10 inches". 2218 * * When formatting 1.50, the output will be "4 feet and 11 inches". 2219 * 2220 * The input unit specified via unit() determines the type of measurement 2221 * being formatted (e.g. "length" when the unit is "foot"). The usage 2222 * requested will be looked for only within this category of measurement 2223 * units. 2224 * 2225 * The output unit can be found via FormattedNumber::getOutputUnit(). 2226 * 2227 * If the usage has multiple parts (e.g. "land-agriculture-grain") and does 2228 * not match a known usage preference, the last part will be dropped 2229 * repeatedly until a match is found (e.g. trying "land-agriculture", then 2230 * "land"). If a match is still not found, usage will fall back to 2231 * "default". 2232 * 2233 * Setting usage to an empty string clears the usage (disables usage-based 2234 * localized formatting). 2235 * 2236 * Setting a usage string but not a correct input unit will result in an 2237 * U_ILLEGAL_ARGUMENT_ERROR. 2238 * 2239 * When using usage, specifying rounding or precision is unnecessary. 2240 * Specifying a precision in some manner will override the default 2241 * formatting. 2242 * 2243 * @param usage A `usage` parameter from the units resource. See the 2244 * unitPreferenceData in *source/data/misc/units.txt*, generated from 2245 * `unitPreferenceData` in [CLDR's 2246 * supplemental/units.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/units.xml). 2247 * @return The fluent chain. 2248 * @stable ICU 68 2249 */ 2250 Derived usage(StringPiece usage) const &; 2251 2252 /** 2253 * Overload of usage() for use on an rvalue reference. 2254 * 2255 * @param usage The unit `usage`. 2256 * @return The fluent chain. 2257 * @stable ICU 68 2258 */ 2259 Derived usage(StringPiece usage) &&; 2260 2261 /** 2262 * Specifies the DisplayOptions. For example, UDisplayOptionsGrammaticalCase specifies 2263 * the desired case for a unit formatter's output (e.g. accusative, dative, genitive). 2264 * 2265 * @param displayOptions 2266 * @return The fluent chain. 2267 * @stable ICU 72 2268 */ 2269 Derived displayOptions(const DisplayOptions &displayOptions) const &; 2270 2271 /** 2272 * Overload of displayOptions() for use on an rvalue reference. 2273 * 2274 * @param displayOptions 2275 * @return The fluent chain. 2276 * @stable ICU 72 2277 */ 2278 Derived displayOptions(const DisplayOptions &displayOptions) &&; 2279 2280 #ifndef U_HIDE_INTERNAL_API 2281 /** 2282 * NOTE: Use `displayOptions` instead. This method was part of 2283 * an internal technology preview in ICU 69, but will be removed 2284 * in ICU 73, in favor of `displayOptions` 2285 * 2286 * Specifies the desired case for a unit formatter's output (e.g. 2287 * accusative, dative, genitive). 2288 * 2289 * @internal 2290 */ 2291 Derived unitDisplayCase(StringPiece unitDisplayCase) const &; 2292 2293 /** 2294 * NOTE: Use `displayOptions` instead. This method was part of 2295 * an internal technology preview in ICU 69, but will be removed 2296 * in ICU 73, in favor of `displayOptions` 2297 * 2298 * Overload of unitDisplayCase() for use on an rvalue reference. 2299 * 2300 * @internal 2301 */ 2302 Derived unitDisplayCase(StringPiece unitDisplayCase) &&; 2303 #endif // U_HIDE_INTERNAL_API 2304 2305 #ifndef U_HIDE_INTERNAL_API 2306 2307 /** 2308 * Set the padding strategy. May be added in the future; see #13338. 2309 * 2310 * @internal ICU 60: This API is ICU internal only. 2311 */ 2312 Derived padding(const impl::Padder &padder) const &; 2313 2314 /** @internal */ 2315 Derived padding(const impl::Padder &padder) &&; 2316 2317 /** 2318 * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to 2319 * be built right away. A threshold of 0 prevents the data structures from being built. 2320 * 2321 * @internal ICU 60: This API is ICU internal only. 2322 */ 2323 Derived threshold(int32_t threshold) const &; 2324 2325 /** @internal */ 2326 Derived threshold(int32_t threshold) &&; 2327 2328 /** 2329 * Internal fluent setter to overwrite the entire macros object. 2330 * 2331 * @internal ICU 60: This API is ICU internal only. 2332 */ 2333 Derived macros(const impl::MacroProps& macros) const &; 2334 2335 /** @internal */ 2336 Derived macros(const impl::MacroProps& macros) &&; 2337 2338 /** @internal */ 2339 Derived macros(impl::MacroProps&& macros) const &; 2340 2341 /** @internal */ 2342 Derived macros(impl::MacroProps&& macros) &&; 2343 2344 #endif /* U_HIDE_INTERNAL_API */ 2345 2346 /** 2347 * Creates a skeleton string representation of this number formatter. A skeleton string is a 2348 * locale-agnostic serialized form of a number formatter. 2349 * 2350 * Not all options are capable of being represented in the skeleton string; for example, a 2351 * DecimalFormatSymbols object. If any such option is encountered, the error code is set to 2352 * U_UNSUPPORTED_ERROR. 2353 * 2354 * The returned skeleton is in normalized form, such that two number formatters with equivalent 2355 * behavior should produce the same skeleton. 2356 * 2357 * For more information on number skeleton strings, see: 2358 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2359 * 2360 * @return A number skeleton string with behavior corresponding to this number formatter. 2361 * @stable ICU 62 2362 */ 2363 UnicodeString toSkeleton(UErrorCode& status) const; 2364 2365 /** 2366 * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer 2367 * wrapping a heap-allocated copy of the current object. 2368 * 2369 * This is equivalent to new-ing the move constructor with a value object 2370 * as the argument. 2371 * 2372 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped 2373 * nullptr on failure. 2374 * @stable ICU 64 2375 */ 2376 LocalPointer<Derived> clone() const &; 2377 2378 /** 2379 * Overload of clone for use on an rvalue reference. 2380 * 2381 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped 2382 * nullptr on failure. 2383 * @stable ICU 64 2384 */ 2385 LocalPointer<Derived> clone() &&; 2386 2387 /** 2388 * Sets the UErrorCode if an error occurred in the fluent chain. 2389 * Preserves older error codes in the outErrorCode. 2390 * @return true if U_FAILURE(outErrorCode) 2391 * @stable ICU 60 2392 */ copyErrorTo(UErrorCode & outErrorCode)2393 UBool copyErrorTo(UErrorCode &outErrorCode) const { 2394 if (U_FAILURE(outErrorCode)) { 2395 // Do not overwrite the older error code 2396 return true; 2397 } 2398 fMacros.copyErrorTo(outErrorCode); 2399 return U_FAILURE(outErrorCode); 2400 } 2401 2402 // NOTE: Uses default copy and move constructors. 2403 2404 private: 2405 impl::MacroProps fMacros; 2406 2407 // Don't construct me directly! Use (Un)LocalizedNumberFormatter. 2408 NumberFormatterSettings() = default; 2409 2410 friend class LocalizedNumberFormatter; 2411 friend class UnlocalizedNumberFormatter; 2412 2413 // Give NumberRangeFormatter access to the MacroProps 2414 friend void impl::touchRangeLocales(impl::RangeMacroProps& macros); 2415 friend class impl::NumberRangeFormatterImpl; 2416 }; 2417 2418 // Explicit instantiations in source/i18n/number_fluent.cpp. 2419 // (MSVC treats imports/exports of explicit instantiations differently.) 2420 #ifndef _MSC_VER 2421 extern template class NumberFormatterSettings<UnlocalizedNumberFormatter>; 2422 extern template class NumberFormatterSettings<LocalizedNumberFormatter>; 2423 #endif 2424 2425 /** 2426 * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified. 2427 * 2428 * Instances of this class are immutable and thread-safe. 2429 * 2430 * @see NumberFormatter 2431 * @stable ICU 60 2432 */ 2433 class U_I18N_API UnlocalizedNumberFormatter 2434 : public NumberFormatterSettings<UnlocalizedNumberFormatter>, public UMemory { 2435 2436 public: 2437 /** 2438 * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols, 2439 * formats, and other data for number display. 2440 * 2441 * @param locale 2442 * The locale to use when loading data for number formatting. 2443 * @return The fluent chain. 2444 * @stable ICU 60 2445 */ 2446 LocalizedNumberFormatter locale(const icu::Locale &locale) const &; 2447 2448 /** 2449 * Overload of locale() for use on an rvalue reference. 2450 * 2451 * @param locale 2452 * The locale to use when loading data for number formatting. 2453 * @return The fluent chain. 2454 * @see #locale 2455 * @stable ICU 62 2456 */ 2457 LocalizedNumberFormatter locale(const icu::Locale &locale) &&; 2458 2459 /** 2460 * Default constructor: puts the formatter into a valid but undefined state. 2461 * 2462 * @stable ICU 62 2463 */ 2464 UnlocalizedNumberFormatter() = default; 2465 2466 /** 2467 * Returns a copy of this UnlocalizedNumberFormatter. 2468 * @stable ICU 60 2469 */ 2470 UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other); 2471 2472 /** 2473 * Move constructor: 2474 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. 2475 * @stable ICU 62 2476 */ 2477 UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) noexcept; 2478 2479 /** 2480 * Copy assignment operator. 2481 * @stable ICU 62 2482 */ 2483 UnlocalizedNumberFormatter& operator=(const UnlocalizedNumberFormatter& other); 2484 2485 /** 2486 * Move assignment operator: 2487 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state. 2488 * @stable ICU 62 2489 */ 2490 UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) noexcept; 2491 2492 private: 2493 explicit UnlocalizedNumberFormatter(const NumberFormatterSettings<UnlocalizedNumberFormatter>& other); 2494 2495 explicit UnlocalizedNumberFormatter( 2496 NumberFormatterSettings<UnlocalizedNumberFormatter>&& src) noexcept; 2497 2498 explicit UnlocalizedNumberFormatter(const impl::MacroProps ¯os); 2499 2500 explicit UnlocalizedNumberFormatter(impl::MacroProps &¯os); 2501 2502 // To give the fluent setters access to this class's constructor: 2503 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>; 2504 2505 // To give NumberFormatter::with() access to this class's constructor: 2506 friend class NumberFormatter; 2507 2508 // To give LNF::withoutLocale() access to this class's constructor: 2509 friend class LocalizedNumberFormatter; 2510 }; 2511 2512 /** 2513 * A NumberFormatter that has a locale associated with it; this means .format() methods are available. 2514 * 2515 * Instances of this class are immutable and thread-safe. 2516 * 2517 * @see NumberFormatter 2518 * @stable ICU 60 2519 */ 2520 class U_I18N_API LocalizedNumberFormatter 2521 : public NumberFormatterSettings<LocalizedNumberFormatter>, public UMemory { 2522 public: 2523 /** 2524 * Format the given integer number to a string using the settings specified in the NumberFormatter fluent 2525 * setting chain. 2526 * 2527 * @param value 2528 * The number to format. 2529 * @param status 2530 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2531 * @return A FormattedNumber object; call .toString() to get the string. 2532 * @stable ICU 60 2533 */ 2534 FormattedNumber formatInt(int64_t value, UErrorCode &status) const; 2535 2536 /** 2537 * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting 2538 * chain. 2539 * 2540 * @param value 2541 * The number to format. 2542 * @param status 2543 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2544 * @return A FormattedNumber object; call .toString() to get the string. 2545 * @stable ICU 60 2546 */ 2547 FormattedNumber formatDouble(double value, UErrorCode &status) const; 2548 2549 /** 2550 * Format the given decimal number to a string using the settings 2551 * specified in the NumberFormatter fluent setting chain. 2552 * The syntax of the unformatted number is a "numeric string" 2553 * as defined in the Decimal Arithmetic Specification, available at 2554 * http://speleotrove.com/decimal 2555 * 2556 * @param value 2557 * The number to format. 2558 * @param status 2559 * Set to an ErrorCode if one occurred in the setter chain or during formatting. 2560 * @return A FormattedNumber object; call .toString() to get the string. 2561 * @stable ICU 60 2562 */ 2563 FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const; 2564 2565 #ifndef U_HIDE_INTERNAL_API 2566 2567 2568 /** 2569 * @internal 2570 */ 2571 const DecimalFormatSymbols* getDecimalFormatSymbols() const; 2572 2573 /** Internal method. 2574 * @internal 2575 */ 2576 FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const; 2577 2578 /** Internal method for DecimalFormat compatibility. 2579 * @internal 2580 */ 2581 void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString& result, UErrorCode& status) const; 2582 2583 /** 2584 * Internal method for testing. 2585 * @internal 2586 */ 2587 const impl::NumberFormatterImpl* getCompiled() const; 2588 2589 /** 2590 * Internal method for testing. 2591 * @internal 2592 */ 2593 int32_t getCallCount() const; 2594 2595 #endif /* U_HIDE_INTERNAL_API */ 2596 2597 /** 2598 * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use 2599 * of this number formatter with APIs that need an object of that type, such as MessageFormat. 2600 * 2601 * This API is not intended to be used other than for enabling API compatibility. The formatDouble, 2602 * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format 2603 * object returned by this method. 2604 * 2605 * The caller owns the returned object and must delete it when finished. 2606 * 2607 * @return A Format wrapping this LocalizedNumberFormatter. 2608 * @stable ICU 62 2609 */ 2610 Format* toFormat(UErrorCode& status) const; 2611 2612 #ifndef U_HIDE_DRAFT_API 2613 /** 2614 * Disassociate the locale from this formatter. 2615 * 2616 * @return The fluent chain. 2617 * @draft ICU 75 2618 */ 2619 UnlocalizedNumberFormatter withoutLocale() const &; 2620 2621 /** 2622 * Overload of withoutLocale() for use on an rvalue reference. 2623 * 2624 * @return The fluent chain. 2625 * @see #withoutLocale 2626 * @draft ICU 75 2627 */ 2628 UnlocalizedNumberFormatter withoutLocale() &&; 2629 #endif // U_HIDE_DRAFT_API 2630 2631 /** 2632 * Default constructor: puts the formatter into a valid but undefined state. 2633 * 2634 * @stable ICU 62 2635 */ 2636 LocalizedNumberFormatter() = default; 2637 2638 /** 2639 * Returns a copy of this LocalizedNumberFormatter. 2640 * @stable ICU 60 2641 */ 2642 LocalizedNumberFormatter(const LocalizedNumberFormatter &other); 2643 2644 /** 2645 * Move constructor: 2646 * The source LocalizedNumberFormatter will be left in a valid but undefined state. 2647 * @stable ICU 62 2648 */ 2649 LocalizedNumberFormatter(LocalizedNumberFormatter&& src) noexcept; 2650 2651 /** 2652 * Copy assignment operator. 2653 * @stable ICU 62 2654 */ 2655 LocalizedNumberFormatter& operator=(const LocalizedNumberFormatter& other); 2656 2657 /** 2658 * Move assignment operator: 2659 * The source LocalizedNumberFormatter will be left in a valid but undefined state. 2660 * @stable ICU 62 2661 */ 2662 LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) noexcept; 2663 2664 #ifndef U_HIDE_INTERNAL_API 2665 2666 /** 2667 * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path 2668 * for the first few calls, and compiling a more efficient data structure if called repeatedly. 2669 * 2670 * <p> 2671 * This function is very hot, being called in every call to the number formatting pipeline. 2672 * 2673 * @param results 2674 * The results object. This method will mutate it to save the results. 2675 * @param status 2676 * @internal 2677 */ 2678 void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const; 2679 2680 #endif /* U_HIDE_INTERNAL_API */ 2681 2682 /** 2683 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own. 2684 * @stable ICU 60 2685 */ 2686 ~LocalizedNumberFormatter(); 2687 2688 private: 2689 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal 2690 // header, and LocalPointer needs the full class definition in order to delete the instance. 2691 const impl::NumberFormatterImpl* fCompiled {nullptr}; 2692 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t 2693 2694 // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter 2695 // from a DecimalFormat. 2696 const impl::DecimalFormatWarehouse* fWarehouse {nullptr}; 2697 2698 explicit LocalizedNumberFormatter(const NumberFormatterSettings<LocalizedNumberFormatter>& other); 2699 2700 explicit LocalizedNumberFormatter(NumberFormatterSettings<LocalizedNumberFormatter>&& src) noexcept; 2701 2702 LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale); 2703 2704 LocalizedNumberFormatter(impl::MacroProps &¯os, const Locale &locale); 2705 2706 void resetCompiled(); 2707 2708 void lnfMoveHelper(LocalizedNumberFormatter&& src); 2709 2710 void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status); 2711 2712 /** 2713 * @return true if the compiled formatter is available. 2714 */ 2715 bool computeCompiled(UErrorCode& status) const; 2716 2717 // To give the fluent setters access to this class's constructor: 2718 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>; 2719 friend class NumberFormatterSettings<LocalizedNumberFormatter>; 2720 2721 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor: 2722 friend class UnlocalizedNumberFormatter; 2723 }; 2724 2725 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) 2726 // Warning 4661. 2727 #pragma warning(pop) 2728 #endif 2729 2730 /** 2731 * See the main description in numberformatter.h for documentation and examples. 2732 * 2733 * @stable ICU 60 2734 */ 2735 class U_I18N_API NumberFormatter final { 2736 public: 2737 /** 2738 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at 2739 * the call site. 2740 * 2741 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining. 2742 * @stable ICU 60 2743 */ 2744 static UnlocalizedNumberFormatter with(); 2745 2746 /** 2747 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call 2748 * site. 2749 * 2750 * @param locale 2751 * The locale from which to load formats and symbols for number formatting. 2752 * @return A {@link LocalizedNumberFormatter}, to be used for chaining. 2753 * @stable ICU 60 2754 */ 2755 static LocalizedNumberFormatter withLocale(const Locale &locale); 2756 2757 /** 2758 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2759 * on a given number skeleton string. 2760 * 2761 * It is possible for an error to occur while parsing. See the overload of this method if you are 2762 * interested in the location of a possible parse error. 2763 * 2764 * For more information on number skeleton strings, see: 2765 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2766 * 2767 * @param skeleton 2768 * The skeleton string off of which to base this NumberFormatter. 2769 * @param status 2770 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2771 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2772 * @stable ICU 62 2773 */ 2774 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status); 2775 2776 /** 2777 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based 2778 * on a given number skeleton string. 2779 * 2780 * If an error occurs while parsing the skeleton string, the offset into the skeleton string at 2781 * which the error occurred will be saved into the UParseError, if provided. 2782 * 2783 * For more information on number skeleton strings, see: 2784 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html 2785 * 2786 * @param skeleton 2787 * The skeleton string off of which to base this NumberFormatter. 2788 * @param perror 2789 * A parse error struct populated if an error occurs when parsing. 2790 * If no error occurs, perror.offset will be set to -1. 2791 * @param status 2792 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid. 2793 * @return An UnlocalizedNumberFormatter, to be used for chaining. 2794 * @stable ICU 64 2795 */ 2796 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, 2797 UParseError& perror, UErrorCode& status); 2798 2799 /** 2800 * Use factory methods instead of the constructor to create a NumberFormatter. 2801 */ 2802 NumberFormatter() = delete; 2803 }; 2804 2805 } // namespace number 2806 U_NAMESPACE_END 2807 2808 #endif /* #if !UCONFIG_NO_FORMATTING */ 2809 2810 #endif /* U_SHOW_CPLUSPLUS_API */ 2811 2812 #endif // __NUMBERFORMATTER_H__ 2813