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