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