Coverage Report

Created: 2025-06-24 06:43

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