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
Notation(const NotationType & type,const NotationUnion & union_)370 Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {}
371
Notation(UErrorCode errorCode)372 Notation(UErrorCode errorCode) : fType(NTN_ERROR) {
373 fUnion.errorCode = errorCode;
374 }
375
Notation()376 Notation() : fType(NTN_SIMPLE), fUnion() {}
377
copyErrorTo(UErrorCode & status)378 UBool copyErrorTo(UErrorCode &status) const {
379 if (fType == NTN_ERROR) {
380 status = fUnion.errorCode;
381 return true;
382 }
383 return false;
384 }
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
Precision(const PrecisionType & type,const PrecisionUnion & union_)730 Precision(const PrecisionType& type, const PrecisionUnion& union_)
731 : fType(type), fUnion(union_) {}
732
Precision(UErrorCode errorCode)733 Precision(UErrorCode errorCode) : fType(RND_ERROR) {
734 fUnion.errorCode = errorCode;
735 }
736
Precision()737 Precision() : fType(RND_BOGUS) {}
738
isBogus()739 bool isBogus() const {
740 return fType == RND_BOGUS;
741 }
742
copyErrorTo(UErrorCode & status)743 UBool copyErrorTo(UErrorCode &status) const {
744 if (fType == RND_ERROR) {
745 status = fUnion.errorCode;
746 return true;
747 }
748 return false;
749 }
750
751 // On the parent type so that this method can be called internally on Precision instances.
752 Precision withCurrency(const CurrencyUnit ¤cy, 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 ¤cy) 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
IntegerWidth(UErrorCode errorCode)995 IntegerWidth(UErrorCode errorCode) { // NOLINT
996 fUnion.errorCode = errorCode;
997 fHasError = true;
998 }
999
IntegerWidth()1000 IntegerWidth() { // NOLINT
1001 fUnion.minMaxInt.fMinInt = -1;
1002 }
1003
1004 /** Returns the default instance. */
standard()1005 static IntegerWidth standard() {
1006 return IntegerWidth::zeroFillTo(1);
1007 }
1008
isBogus()1009 bool isBogus() const {
1010 return !fHasError && fUnion.minMaxInt.fMinInt == -1;
1011 }
1012
copyErrorTo(UErrorCode & status)1013 UBool copyErrorTo(UErrorCode &status) const {
1014 if (fHasError) {
1015 status = fUnion.errorCode;
1016 return true;
1017 }
1018 return false;
1019 }
1020
1021 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const;
1022
1023 bool operator==(const IntegerWidth& other) const;
1024
1025 // To allow MacroProps/MicroProps to initialize empty instances:
1026 friend struct impl::MacroProps;
1027 friend struct impl::MicroProps;
1028
1029 // To allow NumberFormatterImpl to access isBogus():
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
Scale(UErrorCode error)1133 Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {}
1134
Scale()1135 Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {}
1136
isValid()1137 bool isValid() const {
1138 return fMagnitude != 0 || fArbitrary != nullptr;
1139 }
1140
copyErrorTo(UErrorCode & status)1141 UBool copyErrorTo(UErrorCode &status) const {
1142 if (U_FAILURE(fError)) {
1143 status = fError;
1144 return true;
1145 }
1146 return false;
1147 }
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 */
length()1199 int16_t length() const {
1200 return fLength;
1201 }
1202
1203 /** @internal
1204 * Makes a copy of value. Set to "" to unset.
1205 */
1206 void set(StringPiece value);
1207
1208 /** @internal */
isSet()1209 bool isSet() const {
1210 return fLength > 0;
1211 }
1212
1213 #endif // U_HIDE_INTERNAL_API
1214
1215 private:
1216 char *fValue;
1217 int16_t fLength;
1218 UErrorCode fError;
1219
StringProp()1220 StringProp() : fValue(nullptr), fLength(0), fError(U_ZERO_ERROR) {
1221 }
1222
1223 /** @internal (private) */
copyErrorTo(UErrorCode & status)1224 UBool copyErrorTo(UErrorCode &status) const {
1225 if (U_FAILURE(fError)) {
1226 status = fError;
1227 return true;
1228 }
1229 return false;
1230 }
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 */
SymbolsWrapper()1248 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 */
copyErrorTo(UErrorCode & status)1306 UBool copyErrorTo(UErrorCode &status) const {
1307 if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) {
1308 status = U_MEMORY_ALLOCATION_ERROR;
1309 return true;
1310 } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) {
1311 status = U_MEMORY_ALLOCATION_ERROR;
1312 return true;
1313 }
1314 return false;
1315 }
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 */
Grouper(int16_t grouping1,int16_t grouping2,int16_t minGrouping,UNumberGroupingStrategy strategy)1351 Grouper(int16_t grouping1, int16_t grouping2, int16_t minGrouping, UNumberGroupingStrategy strategy)
1352 : fGrouping1(grouping1),
1353 fGrouping2(grouping2),
1354 fMinGrouping(minGrouping),
1355 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
Grouper()1391 Grouper() : fGrouping1(-3) {}
1392
isBogus()1393 bool isBogus() const {
1394 return fGrouping1 == -3;
1395 }
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
Padder(UErrorCode errorCode)1445 Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT
1446 fUnion.errorCode = errorCode;
1447 }
1448
Padder()1449 Padder() : fWidth(-2) {} // NOLINT
1450
isBogus()1451 bool isBogus() const {
1452 return fWidth == -2;
1453 }
1454
copyErrorTo(UErrorCode & status)1455 UBool copyErrorTo(UErrorCode &status) const {
1456 if (fWidth == -3) {
1457 status = fUnion.errorCode;
1458 return true;
1459 }
1460 return false;
1461 }
1462
isValid()1463 bool isValid() const {
1464 return fWidth > 0;
1465 }
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 UNumberDecimalSeparatorDisplay decimal = UNUM_DECIMAL_SEPARATOR_COUNT;
1522
1523 /** @internal */
1524 Scale scale; // = Scale(); (benign value)
1525
1526 /** @internal */
1527 StringProp usage; // = StringProp(); (no usage)
1528
1529 /** @internal */
1530 StringProp unitDisplayCase; // = StringProp(); (nominative)
1531
1532 /** @internal */
1533 const AffixPatternProvider* affixProvider = nullptr; // no ownership
1534
1535 /** @internal */
1536 const PluralRules* rules = nullptr; // no ownership
1537
1538 /** @internal */
1539 int32_t threshold = kInternalDefaultThreshold;
1540
1541 /** @internal */
1542 Locale locale;
1543
1544 // NOTE: Uses default copy and move constructors.
1545
1546 /**
1547 * Check all members for errors.
1548 * @internal
1549 */
copyErrorToMacroProps1550 bool copyErrorTo(UErrorCode &status) const {
1551 return notation.copyErrorTo(status) || precision.copyErrorTo(status) ||
1552 padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) ||
1553 symbols.copyErrorTo(status) || scale.copyErrorTo(status) || usage.copyErrorTo(status) ||
1554 unitDisplayCase.copyErrorTo(status);
1555 }
1556 };
1557
1558 } // namespace impl
1559
1560 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
1561 // Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method
1562 // is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation
1563 // inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is
1564 // fully defined. However, since each translation unit explicitly instantiates all the necessary template classes,
1565 // they will all be passed to the linker, and the linker will still find and export all the class members.
1566 #pragma warning(push)
1567 #pragma warning(disable: 4661)
1568 #endif
1569
1570 /**
1571 * An abstract base class for specifying settings related to number formatting. This class is implemented by
1572 * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. This class is not intended for
1573 * public subclassing.
1574 */
1575 template<typename Derived>
1576 class U_I18N_API NumberFormatterSettings {
1577 public:
1578 /**
1579 * Specifies the notation style (simple, scientific, or compact) for rendering numbers.
1580 *
1581 * <ul>
1582 * <li>Simple notation: "12,300"
1583 * <li>Scientific notation: "1.23E4"
1584 * <li>Compact notation: "12K"
1585 * </ul>
1586 *
1587 * <p>
1588 * All notation styles will be properly localized with locale data, and all notation styles are compatible with
1589 * units, rounding precisions, and other number formatter settings.
1590 *
1591 * <p>
1592 * Pass this method the return value of a {@link Notation} factory method. For example:
1593 *
1594 * <pre>
1595 * NumberFormatter::with().notation(Notation::compactShort())
1596 * </pre>
1597 *
1598 * The default is to use simple notation.
1599 *
1600 * @param notation
1601 * The notation strategy to use.
1602 * @return The fluent chain.
1603 * @see Notation
1604 * @stable ICU 60
1605 */
1606 Derived notation(const Notation ¬ation) const &;
1607
1608 /**
1609 * Overload of notation() for use on an rvalue reference.
1610 *
1611 * @param notation
1612 * The notation strategy to use.
1613 * @return The fluent chain.
1614 * @see #notation
1615 * @stable ICU 62
1616 */
1617 Derived notation(const Notation ¬ation) &&;
1618
1619 /**
1620 * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers.
1621 *
1622 * <ul>
1623 * <li>Unit of measure: "12.3 meters"
1624 * <li>Currency: "$12.30"
1625 * <li>Percent: "12.3%"
1626 * </ul>
1627 *
1628 * All units will be properly localized with locale data, and all units are compatible with notation styles,
1629 * rounding precisions, and other number formatter settings.
1630 *
1631 * \note If the usage() is set, the output unit **will be changed** to
1632 * produce localised units, according to usage, locale and unit. See
1633 * FormattedNumber::getOutputUnit().
1634 *
1635 * Pass this method any instance of {@link MeasureUnit}. For units of measure:
1636 *
1637 * <pre>
1638 * NumberFormatter::with().unit(MeasureUnit::getMeter())
1639 * NumberFormatter::with().unit(MeasureUnit::forIdentifier("foot-per-second", status))
1640 * </pre>
1641 *
1642 * Currency:
1643 *
1644 * <pre>
1645 * NumberFormatter::with().unit(CurrencyUnit(u"USD", status))
1646 * </pre>
1647 *
1648 * Percent:
1649 *
1650 * <pre>
1651 * NumberFormatter::with().unit(NoUnit.percent())
1652 * </pre>
1653 *
1654 * See {@link #perUnit} for information on how to format strings like "5 meters per second".
1655 *
1656 * The default is to render without units (equivalent to NoUnit.base()).
1657 *
1658 * @param unit
1659 * The unit to render.
1660 * @return The fluent chain.
1661 * @see MeasureUnit
1662 * @see Currency
1663 * @see NoUnit
1664 * @see #perUnit
1665 * @stable ICU 60
1666 */
1667 Derived unit(const icu::MeasureUnit &unit) const &;
1668
1669 /**
1670 * Overload of unit() for use on an rvalue reference.
1671 *
1672 * @param unit
1673 * The unit to render.
1674 * @return The fluent chain.
1675 * @see #unit
1676 * @stable ICU 62
1677 */
1678 Derived unit(const icu::MeasureUnit &unit) &&;
1679
1680 /**
1681 * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
1682 * methods that return pointers that need ownership.
1683 *
1684 * Note: consider using the MeasureFormat factory methods that return by value.
1685 *
1686 * @param unit
1687 * The unit to render.
1688 * @return The fluent chain.
1689 * @see #unit
1690 * @see MeasureUnit
1691 * @stable ICU 60
1692 */
1693 Derived adoptUnit(icu::MeasureUnit *unit) const &;
1694
1695 /**
1696 * Overload of adoptUnit() for use on an rvalue reference.
1697 *
1698 * @param unit
1699 * The unit to render.
1700 * @return The fluent chain.
1701 * @see #adoptUnit
1702 * @stable ICU 62
1703 */
1704 Derived adoptUnit(icu::MeasureUnit *unit) &&;
1705
1706 /**
1707 * Sets a unit to be used in the denominator. For example, to format "3 m/s", pass METER to the unit and SECOND to
1708 * the perUnit.
1709 *
1710 * Pass this method any instance of {@link MeasureUnit}. Example:
1711 *
1712 * <pre>
1713 * NumberFormatter::with()
1714 * .unit(MeasureUnit::getMeter())
1715 * .perUnit(MeasureUnit::getSecond())
1716 * </pre>
1717 *
1718 * The default is not to display any unit in the denominator.
1719 *
1720 * If a per-unit is specified without a primary unit via {@link #unit}, the behavior is undefined.
1721 *
1722 * @param perUnit
1723 * The unit to render in the denominator.
1724 * @return The fluent chain
1725 * @see #unit
1726 * @stable ICU 61
1727 */
1728 Derived perUnit(const icu::MeasureUnit &perUnit) const &;
1729
1730 /**
1731 * Overload of perUnit() for use on an rvalue reference.
1732 *
1733 * @param perUnit
1734 * The unit to render in the denominator.
1735 * @return The fluent chain.
1736 * @see #perUnit
1737 * @stable ICU 62
1738 */
1739 Derived perUnit(const icu::MeasureUnit &perUnit) &&;
1740
1741 /**
1742 * Like perUnit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
1743 * methods that return pointers that need ownership.
1744 *
1745 * Note: consider using the MeasureFormat factory methods that return by value.
1746 *
1747 * @param perUnit
1748 * The unit to render in the denominator.
1749 * @return The fluent chain.
1750 * @see #perUnit
1751 * @see MeasureUnit
1752 * @stable ICU 61
1753 */
1754 Derived adoptPerUnit(icu::MeasureUnit *perUnit) const &;
1755
1756 /**
1757 * Overload of adoptPerUnit() for use on an rvalue reference.
1758 *
1759 * @param perUnit
1760 * The unit to render in the denominator.
1761 * @return The fluent chain.
1762 * @see #adoptPerUnit
1763 * @stable ICU 62
1764 */
1765 Derived adoptPerUnit(icu::MeasureUnit *perUnit) &&;
1766
1767 /**
1768 * Specifies the rounding precision to use when formatting numbers.
1769 *
1770 * <ul>
1771 * <li>Round to 3 decimal places: "3.142"
1772 * <li>Round to 3 significant figures: "3.14"
1773 * <li>Round to the closest nickel: "3.15"
1774 * <li>Do not perform rounding: "3.1415926..."
1775 * </ul>
1776 *
1777 * <p>
1778 * Pass this method the return value of one of the factory methods on {@link Precision}. For example:
1779 *
1780 * <pre>
1781 * NumberFormatter::with().precision(Precision::fixedFraction(2))
1782 * </pre>
1783 *
1784 * <p>
1785 * In most cases, the default rounding strategy is to round to 6 fraction places; i.e.,
1786 * <code>Precision.maxFraction(6)</code>. The exceptions are if compact notation is being used, then the compact
1787 * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency,
1788 * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for
1789 * details).
1790 *
1791 * @param precision
1792 * The rounding precision to use.
1793 * @return The fluent chain.
1794 * @see Precision
1795 * @stable ICU 62
1796 */
1797 Derived precision(const Precision& precision) const &;
1798
1799 /**
1800 * Overload of precision() for use on an rvalue reference.
1801 *
1802 * @param precision
1803 * The rounding precision to use.
1804 * @return The fluent chain.
1805 * @see #precision
1806 * @stable ICU 62
1807 */
1808 Derived precision(const Precision& precision) &&;
1809
1810 /**
1811 * Specifies how to determine the direction to round a number when it has more digits than fit in the
1812 * desired precision. When formatting 1.235:
1813 *
1814 * <ul>
1815 * <li>Ceiling rounding mode with integer precision: "2"
1816 * <li>Half-down rounding mode with 2 fixed fraction digits: "1.23"
1817 * <li>Half-up rounding mode with 2 fixed fraction digits: "1.24"
1818 * </ul>
1819 *
1820 * The default is HALF_EVEN. For more information on rounding mode, see the ICU userguide here:
1821 *
1822 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes
1823 *
1824 * @param roundingMode The rounding mode to use.
1825 * @return The fluent chain.
1826 * @stable ICU 62
1827 */
1828 Derived roundingMode(UNumberFormatRoundingMode roundingMode) const &;
1829
1830 /**
1831 * Overload of roundingMode() for use on an rvalue reference.
1832 *
1833 * @param roundingMode The rounding mode to use.
1834 * @return The fluent chain.
1835 * @see #roundingMode
1836 * @stable ICU 62
1837 */
1838 Derived roundingMode(UNumberFormatRoundingMode roundingMode) &&;
1839
1840 /**
1841 * Specifies the grouping strategy to use when formatting numbers.
1842 *
1843 * <ul>
1844 * <li>Default grouping: "12,300" and "1,230"
1845 * <li>Grouping with at least 2 digits: "12,300" and "1230"
1846 * <li>No grouping: "12300" and "1230"
1847 * </ul>
1848 *
1849 * <p>
1850 * The exact grouping widths will be chosen based on the locale.
1851 *
1852 * <p>
1853 * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example:
1854 *
1855 * <pre>
1856 * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2)
1857 * </pre>
1858 *
1859 * The default is to perform grouping according to locale data; most locales, but not all locales,
1860 * enable it by default.
1861 *
1862 * @param strategy
1863 * The grouping strategy to use.
1864 * @return The fluent chain.
1865 * @stable ICU 61
1866 */
1867 Derived grouping(UNumberGroupingStrategy strategy) const &;
1868
1869 /**
1870 * Overload of grouping() for use on an rvalue reference.
1871 *
1872 * @param strategy
1873 * The grouping strategy to use.
1874 * @return The fluent chain.
1875 * @see #grouping
1876 * @stable ICU 62
1877 */
1878 Derived grouping(UNumberGroupingStrategy strategy) &&;
1879
1880 /**
1881 * Specifies the minimum and maximum number of digits to render before the decimal mark.
1882 *
1883 * <ul>
1884 * <li>Zero minimum integer digits: ".08"
1885 * <li>One minimum integer digit: "0.08"
1886 * <li>Two minimum integer digits: "00.08"
1887 * </ul>
1888 *
1889 * <p>
1890 * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example:
1891 *
1892 * <pre>
1893 * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2))
1894 * </pre>
1895 *
1896 * The default is to have one minimum integer digit.
1897 *
1898 * @param style
1899 * The integer width to use.
1900 * @return The fluent chain.
1901 * @see IntegerWidth
1902 * @stable ICU 60
1903 */
1904 Derived integerWidth(const IntegerWidth &style) const &;
1905
1906 /**
1907 * Overload of integerWidth() for use on an rvalue reference.
1908 *
1909 * @param style
1910 * The integer width to use.
1911 * @return The fluent chain.
1912 * @see #integerWidth
1913 * @stable ICU 62
1914 */
1915 Derived integerWidth(const IntegerWidth &style) &&;
1916
1917 /**
1918 * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering
1919 * numbers.
1920 *
1921 * <ul>
1922 * <li><em>en_US</em> symbols: "12,345.67"
1923 * <li><em>fr_FR</em> symbols: "12 345,67"
1924 * <li><em>de_CH</em> symbols: "12’345.67"
1925 * <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇"
1926 * </ul>
1927 *
1928 * <p>
1929 * Pass this method an instance of {@link DecimalFormatSymbols}. For example:
1930 *
1931 * <pre>
1932 * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status))
1933 * </pre>
1934 *
1935 * <p>
1936 * <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale.
1937 * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar
1938 * numbering system.
1939 *
1940 * <p>
1941 * <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object
1942 * after passing it into the fluent chain will not be seen.
1943 *
1944 * <p>
1945 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
1946 * or NumberingSystem.
1947 *
1948 * <p>
1949 * The default is to choose the symbols based on the locale specified in the fluent chain.
1950 *
1951 * @param symbols
1952 * The DecimalFormatSymbols to use.
1953 * @return The fluent chain.
1954 * @see DecimalFormatSymbols
1955 * @stable ICU 60
1956 */
1957 Derived symbols(const DecimalFormatSymbols &symbols) const &;
1958
1959 /**
1960 * Overload of symbols() for use on an rvalue reference.
1961 *
1962 * @param symbols
1963 * The DecimalFormatSymbols to use.
1964 * @return The fluent chain.
1965 * @see #symbols
1966 * @stable ICU 62
1967 */
1968 Derived symbols(const DecimalFormatSymbols &symbols) &&;
1969
1970 /**
1971 * Specifies that the given numbering system should be used when fetching symbols.
1972 *
1973 * <ul>
1974 * <li>Latin numbering system: "12,345"
1975 * <li>Myanmar numbering system: "၁၂,၃၄၅"
1976 * <li>Math Sans Bold numbering system: ","
1977 * </ul>
1978 *
1979 * <p>
1980 * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin
1981 * alphabet numbering system (ASCII digits):
1982 *
1983 * <pre>
1984 * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status))
1985 * </pre>
1986 *
1987 * <p>
1988 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
1989 * or NumberingSystem.
1990 *
1991 * <p>
1992 * The default is to choose the best numbering system for the locale.
1993 *
1994 * <p>
1995 * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods.
1996 *
1997 * @param symbols
1998 * The NumberingSystem to use.
1999 * @return The fluent chain.
2000 * @see NumberingSystem
2001 * @stable ICU 60
2002 */
2003 Derived adoptSymbols(NumberingSystem *symbols) const &;
2004
2005 /**
2006 * Overload of adoptSymbols() for use on an rvalue reference.
2007 *
2008 * @param symbols
2009 * The NumberingSystem to use.
2010 * @return The fluent chain.
2011 * @see #adoptSymbols
2012 * @stable ICU 62
2013 */
2014 Derived adoptSymbols(NumberingSystem *symbols) &&;
2015
2016 /**
2017 * Sets the width of the unit (measure unit or currency). Most common values:
2018 *
2019 * <ul>
2020 * <li>Short: "$12.00", "12 m"
2021 * <li>ISO Code: "USD 12.00"
2022 * <li>Full name: "12.00 US dollars", "12 meters"
2023 * </ul>
2024 *
2025 * <p>
2026 * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example:
2027 *
2028 * <pre>
2029 * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
2030 * </pre>
2031 *
2032 * <p>
2033 * The default is the SHORT width.
2034 *
2035 * @param width
2036 * The width to use when rendering numbers.
2037 * @return The fluent chain
2038 * @see UNumberUnitWidth
2039 * @stable ICU 60
2040 */
2041 Derived unitWidth(UNumberUnitWidth width) const &;
2042
2043 /**
2044 * Overload of unitWidth() for use on an rvalue reference.
2045 *
2046 * @param width
2047 * The width to use when rendering numbers.
2048 * @return The fluent chain.
2049 * @see #unitWidth
2050 * @stable ICU 62
2051 */
2052 Derived unitWidth(UNumberUnitWidth width) &&;
2053
2054 /**
2055 * Sets the plus/minus sign display strategy. Most common values:
2056 *
2057 * <ul>
2058 * <li>Auto: "123", "-123"
2059 * <li>Always: "+123", "-123"
2060 * <li>Accounting: "$123", "($123)"
2061 * </ul>
2062 *
2063 * <p>
2064 * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example:
2065 *
2066 * <pre>
2067 * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
2068 * </pre>
2069 *
2070 * <p>
2071 * The default is AUTO sign display.
2072 *
2073 * @param style
2074 * The sign display strategy to use when rendering numbers.
2075 * @return The fluent chain
2076 * @see UNumberSignDisplay
2077 * @stable ICU 60
2078 */
2079 Derived sign(UNumberSignDisplay style) const &;
2080
2081 /**
2082 * Overload of sign() for use on an rvalue reference.
2083 *
2084 * @param style
2085 * The sign display strategy to use when rendering numbers.
2086 * @return The fluent chain.
2087 * @see #sign
2088 * @stable ICU 62
2089 */
2090 Derived sign(UNumberSignDisplay style) &&;
2091
2092 /**
2093 * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common
2094 * values:
2095 *
2096 * <ul>
2097 * <li>Auto: "1"
2098 * <li>Always: "1."
2099 * </ul>
2100 *
2101 * <p>
2102 * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example:
2103 *
2104 * <pre>
2105 * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS)
2106 * </pre>
2107 *
2108 * <p>
2109 * The default is AUTO decimal separator display.
2110 *
2111 * @param style
2112 * The decimal separator display strategy to use when rendering numbers.
2113 * @return The fluent chain
2114 * @see UNumberDecimalSeparatorDisplay
2115 * @stable ICU 60
2116 */
2117 Derived decimal(UNumberDecimalSeparatorDisplay style) const &;
2118
2119 /**
2120 * Overload of decimal() for use on an rvalue reference.
2121 *
2122 * @param style
2123 * The decimal separator display strategy to use when rendering numbers.
2124 * @return The fluent chain.
2125 * @see #decimal
2126 * @stable ICU 62
2127 */
2128 Derived decimal(UNumberDecimalSeparatorDisplay style) &&;
2129
2130 /**
2131 * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting.
2132 * Most common values:
2133 *
2134 * <ul>
2135 * <li>Multiply by 100: useful for percentages.
2136 * <li>Multiply by an arbitrary value: useful for unit conversions.
2137 * </ul>
2138 *
2139 * <p>
2140 * Pass an element from a {@link Scale} factory method to this setter. For example:
2141 *
2142 * <pre>
2143 * NumberFormatter::with().scale(Scale::powerOfTen(2))
2144 * </pre>
2145 *
2146 * <p>
2147 * The default is to not apply any multiplier.
2148 *
2149 * @param scale
2150 * The scale to apply when rendering numbers.
2151 * @return The fluent chain
2152 * @stable ICU 62
2153 */
2154 Derived scale(const Scale &scale) const &;
2155
2156 /**
2157 * Overload of scale() for use on an rvalue reference.
2158 *
2159 * @param scale
2160 * The scale to apply when rendering numbers.
2161 * @return The fluent chain.
2162 * @see #scale
2163 * @stable ICU 62
2164 */
2165 Derived scale(const Scale &scale) &&;
2166
2167 #ifndef U_HIDE_DRAFT_API
2168 /**
2169 * Specifies the usage for which numbers will be formatted ("person-height",
2170 * "road", "rainfall", etc.)
2171 *
2172 * When a `usage` is specified, the output unit will change depending on the
2173 * `Locale` and the unit quantity. For example, formatting length
2174 * measurements specified in meters:
2175 *
2176 * `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")`
2177 * * When formatting 0.25, the output will be "10 inches".
2178 * * When formatting 1.50, the output will be "4 feet and 11 inches".
2179 *
2180 * The input unit specified via unit() determines the type of measurement
2181 * being formatted (e.g. "length" when the unit is "foot"). The usage
2182 * requested will be looked for only within this category of measurement
2183 * units.
2184 *
2185 * The output unit can be found via FormattedNumber::getOutputUnit().
2186 *
2187 * If the usage has multiple parts (e.g. "land-agriculture-grain") and does
2188 * not match a known usage preference, the last part will be dropped
2189 * repeatedly until a match is found (e.g. trying "land-agriculture", then
2190 * "land"). If a match is still not found, usage will fall back to
2191 * "default".
2192 *
2193 * Setting usage to an empty string clears the usage (disables usage-based
2194 * localized formatting).
2195 *
2196 * Setting a usage string but not a correct input unit will result in an
2197 * U_ILLEGAL_ARGUMENT_ERROR.
2198 *
2199 * When using usage, specifying rounding or precision is unnecessary.
2200 * Specifying a precision in some manner will override the default
2201 * formatting.
2202 *
2203 * @param usage A `usage` parameter from the units resource. See the
2204 * unitPreferenceData in *source/data/misc/units.txt*, generated from
2205 * `unitPreferenceData` in [CLDR's
2206 * supplemental/units.xml](https://github.com/unicode-org/cldr/blob/master/common/supplemental/units.xml).
2207 * @return The fluent chain.
2208 * @draft ICU 68
2209 */
2210 Derived usage(StringPiece usage) const &;
2211
2212 /**
2213 * Overload of usage() for use on an rvalue reference.
2214 *
2215 * @param usage The unit `usage`.
2216 * @return The fluent chain.
2217 * @draft ICU 68
2218 */
2219 Derived usage(StringPiece usage) &&;
2220 #endif // U_HIDE_DRAFT_API
2221
2222 #ifndef U_HIDE_DRAFT_API
2223 #ifndef U_HIDE_INTERNAL_API
2224 /**
2225 * Specifies the desired case for a unit formatter's output (e.g.
2226 * accusative, dative, genitive).
2227 *
2228 * @internal ICU 69 technology preview
2229 */
2230 Derived unitDisplayCase(StringPiece unitDisplayCase) const &;
2231
2232 /**
2233 * Overload of unitDisplayCase() for use on an rvalue reference.
2234 *
2235 * @internal ICU 69 technology preview
2236 */
2237 Derived unitDisplayCase(StringPiece unitDisplayCase) &&;
2238 #endif // U_HIDE_INTERNAL_API
2239 #endif // U_HIDE_DRAFT_API
2240
2241 #ifndef U_HIDE_INTERNAL_API
2242
2243 /**
2244 * Set the padding strategy. May be added in the future; see #13338.
2245 *
2246 * @internal ICU 60: This API is ICU internal only.
2247 */
2248 Derived padding(const impl::Padder &padder) const &;
2249
2250 /** @internal */
2251 Derived padding(const impl::Padder &padder) &&;
2252
2253 /**
2254 * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to
2255 * be built right away. A threshold of 0 prevents the data structures from being built.
2256 *
2257 * @internal ICU 60: This API is ICU internal only.
2258 */
2259 Derived threshold(int32_t threshold) const &;
2260
2261 /** @internal */
2262 Derived threshold(int32_t threshold) &&;
2263
2264 /**
2265 * Internal fluent setter to overwrite the entire macros object.
2266 *
2267 * @internal ICU 60: This API is ICU internal only.
2268 */
2269 Derived macros(const impl::MacroProps& macros) const &;
2270
2271 /** @internal */
2272 Derived macros(const impl::MacroProps& macros) &&;
2273
2274 /** @internal */
2275 Derived macros(impl::MacroProps&& macros) const &;
2276
2277 /** @internal */
2278 Derived macros(impl::MacroProps&& macros) &&;
2279
2280 #endif /* U_HIDE_INTERNAL_API */
2281
2282 /**
2283 * Creates a skeleton string representation of this number formatter. A skeleton string is a
2284 * locale-agnostic serialized form of a number formatter.
2285 *
2286 * Not all options are capable of being represented in the skeleton string; for example, a
2287 * DecimalFormatSymbols object. If any such option is encountered, the error code is set to
2288 * U_UNSUPPORTED_ERROR.
2289 *
2290 * The returned skeleton is in normalized form, such that two number formatters with equivalent
2291 * behavior should produce the same skeleton.
2292 *
2293 * For more information on number skeleton strings, see:
2294 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
2295 *
2296 * @return A number skeleton string with behavior corresponding to this number formatter.
2297 * @stable ICU 62
2298 */
2299 UnicodeString toSkeleton(UErrorCode& status) const;
2300
2301 /**
2302 * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer
2303 * wrapping a heap-allocated copy of the current object.
2304 *
2305 * This is equivalent to new-ing the move constructor with a value object
2306 * as the argument.
2307 *
2308 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
2309 * nullptr on failure.
2310 * @stable ICU 64
2311 */
2312 LocalPointer<Derived> clone() const &;
2313
2314 /**
2315 * Overload of clone for use on an rvalue reference.
2316 *
2317 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
2318 * nullptr on failure.
2319 * @stable ICU 64
2320 */
2321 LocalPointer<Derived> clone() &&;
2322
2323 /**
2324 * Sets the UErrorCode if an error occurred in the fluent chain.
2325 * Preserves older error codes in the outErrorCode.
2326 * @return true if U_FAILURE(outErrorCode)
2327 * @stable ICU 60
2328 */
copyErrorTo(UErrorCode & outErrorCode)2329 UBool copyErrorTo(UErrorCode &outErrorCode) const {
2330 if (U_FAILURE(outErrorCode)) {
2331 // Do not overwrite the older error code
2332 return true;
2333 }
2334 fMacros.copyErrorTo(outErrorCode);
2335 return U_FAILURE(outErrorCode);
2336 }
2337
2338 // NOTE: Uses default copy and move constructors.
2339
2340 private:
2341 impl::MacroProps fMacros;
2342
2343 // Don't construct me directly! Use (Un)LocalizedNumberFormatter.
2344 NumberFormatterSettings() = default;
2345
2346 friend class LocalizedNumberFormatter;
2347 friend class UnlocalizedNumberFormatter;
2348
2349 // Give NumberRangeFormatter access to the MacroProps
2350 friend void impl::touchRangeLocales(impl::RangeMacroProps& macros);
2351 friend class impl::NumberRangeFormatterImpl;
2352 };
2353
2354 /**
2355 * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified.
2356 *
2357 * Instances of this class are immutable and thread-safe.
2358 *
2359 * @see NumberFormatter
2360 * @stable ICU 60
2361 */
2362 class U_I18N_API UnlocalizedNumberFormatter
2363 : public NumberFormatterSettings<UnlocalizedNumberFormatter>, public UMemory {
2364
2365 public:
2366 /**
2367 * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols,
2368 * formats, and other data for number display.
2369 *
2370 * @param locale
2371 * The locale to use when loading data for number formatting.
2372 * @return The fluent chain.
2373 * @stable ICU 60
2374 */
2375 LocalizedNumberFormatter locale(const icu::Locale &locale) const &;
2376
2377 /**
2378 * Overload of locale() for use on an rvalue reference.
2379 *
2380 * @param locale
2381 * The locale to use when loading data for number formatting.
2382 * @return The fluent chain.
2383 * @see #locale
2384 * @stable ICU 62
2385 */
2386 LocalizedNumberFormatter locale(const icu::Locale &locale) &&;
2387
2388 /**
2389 * Default constructor: puts the formatter into a valid but undefined state.
2390 *
2391 * @stable ICU 62
2392 */
2393 UnlocalizedNumberFormatter() = default;
2394
2395 /**
2396 * Returns a copy of this UnlocalizedNumberFormatter.
2397 * @stable ICU 60
2398 */
2399 UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other);
2400
2401 /**
2402 * Move constructor:
2403 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
2404 * @stable ICU 62
2405 */
2406 UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) U_NOEXCEPT;
2407
2408 /**
2409 * Copy assignment operator.
2410 * @stable ICU 62
2411 */
2412 UnlocalizedNumberFormatter& operator=(const UnlocalizedNumberFormatter& other);
2413
2414 /**
2415 * Move assignment operator:
2416 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
2417 * @stable ICU 62
2418 */
2419 UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) U_NOEXCEPT;
2420
2421 private:
2422 explicit UnlocalizedNumberFormatter(const NumberFormatterSettings<UnlocalizedNumberFormatter>& other);
2423
2424 explicit UnlocalizedNumberFormatter(
2425 NumberFormatterSettings<UnlocalizedNumberFormatter>&& src) U_NOEXCEPT;
2426
2427 // To give the fluent setters access to this class's constructor:
2428 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
2429
2430 // To give NumberFormatter::with() access to this class's constructor:
2431 friend class NumberFormatter;
2432 };
2433
2434 /**
2435 * A NumberFormatter that has a locale associated with it; this means .format() methods are available.
2436 *
2437 * Instances of this class are immutable and thread-safe.
2438 *
2439 * @see NumberFormatter
2440 * @stable ICU 60
2441 */
2442 class U_I18N_API LocalizedNumberFormatter
2443 : public NumberFormatterSettings<LocalizedNumberFormatter>, public UMemory {
2444 public:
2445 /**
2446 * Format the given integer number to a string using the settings specified in the NumberFormatter fluent
2447 * setting chain.
2448 *
2449 * @param value
2450 * The number to format.
2451 * @param status
2452 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2453 * @return A FormattedNumber object; call .toString() to get the string.
2454 * @stable ICU 60
2455 */
2456 FormattedNumber formatInt(int64_t value, UErrorCode &status) const;
2457
2458 /**
2459 * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting
2460 * chain.
2461 *
2462 * @param value
2463 * The number to format.
2464 * @param status
2465 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2466 * @return A FormattedNumber object; call .toString() to get the string.
2467 * @stable ICU 60
2468 */
2469 FormattedNumber formatDouble(double value, UErrorCode &status) const;
2470
2471 /**
2472 * Format the given decimal number to a string using the settings
2473 * specified in the NumberFormatter fluent setting chain.
2474 * The syntax of the unformatted number is a "numeric string"
2475 * as defined in the Decimal Arithmetic Specification, available at
2476 * http://speleotrove.com/decimal
2477 *
2478 * @param value
2479 * The number to format.
2480 * @param status
2481 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2482 * @return A FormattedNumber object; call .toString() to get the string.
2483 * @stable ICU 60
2484 */
2485 FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const;
2486
2487 #ifndef U_HIDE_INTERNAL_API
2488
2489 /** Internal method.
2490 * @internal
2491 */
2492 FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const;
2493
2494 /** Internal method for DecimalFormat compatibility.
2495 * @internal
2496 */
2497 void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString& result, UErrorCode& status) const;
2498
2499 /**
2500 * Internal method for testing.
2501 * @internal
2502 */
2503 const impl::NumberFormatterImpl* getCompiled() const;
2504
2505 /**
2506 * Internal method for testing.
2507 * @internal
2508 */
2509 int32_t getCallCount() const;
2510
2511 #endif /* U_HIDE_INTERNAL_API */
2512
2513 /**
2514 * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use
2515 * of this number formatter with APIs that need an object of that type, such as MessageFormat.
2516 *
2517 * This API is not intended to be used other than for enabling API compatibility. The formatDouble,
2518 * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format
2519 * object returned by this method.
2520 *
2521 * The caller owns the returned object and must delete it when finished.
2522 *
2523 * @return A Format wrapping this LocalizedNumberFormatter.
2524 * @stable ICU 62
2525 */
2526 Format* toFormat(UErrorCode& status) const;
2527
2528 /**
2529 * Default constructor: puts the formatter into a valid but undefined state.
2530 *
2531 * @stable ICU 62
2532 */
2533 LocalizedNumberFormatter() = default;
2534
2535 /**
2536 * Returns a copy of this LocalizedNumberFormatter.
2537 * @stable ICU 60
2538 */
2539 LocalizedNumberFormatter(const LocalizedNumberFormatter &other);
2540
2541 /**
2542 * Move constructor:
2543 * The source LocalizedNumberFormatter will be left in a valid but undefined state.
2544 * @stable ICU 62
2545 */
2546 LocalizedNumberFormatter(LocalizedNumberFormatter&& src) U_NOEXCEPT;
2547
2548 /**
2549 * Copy assignment operator.
2550 * @stable ICU 62
2551 */
2552 LocalizedNumberFormatter& operator=(const LocalizedNumberFormatter& other);
2553
2554 /**
2555 * Move assignment operator:
2556 * The source LocalizedNumberFormatter will be left in a valid but undefined state.
2557 * @stable ICU 62
2558 */
2559 LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) U_NOEXCEPT;
2560
2561 #ifndef U_HIDE_INTERNAL_API
2562
2563 /**
2564 * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path
2565 * for the first few calls, and compiling a more efficient data structure if called repeatedly.
2566 *
2567 * <p>
2568 * This function is very hot, being called in every call to the number formatting pipeline.
2569 *
2570 * @param results
2571 * The results object. This method will mutate it to save the results.
2572 * @param status
2573 * @internal
2574 */
2575 void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const;
2576
2577 #endif /* U_HIDE_INTERNAL_API */
2578
2579 /**
2580 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own.
2581 * @stable ICU 60
2582 */
2583 ~LocalizedNumberFormatter();
2584
2585 private:
2586 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal
2587 // header, and LocalPointer needs the full class definition in order to delete the instance.
2588 const impl::NumberFormatterImpl* fCompiled {nullptr};
2589 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t
2590
2591 // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter
2592 // from a DecimalFormat.
2593 const impl::DecimalFormatWarehouse* fWarehouse {nullptr};
2594
2595 explicit LocalizedNumberFormatter(const NumberFormatterSettings<LocalizedNumberFormatter>& other);
2596
2597 explicit LocalizedNumberFormatter(NumberFormatterSettings<LocalizedNumberFormatter>&& src) U_NOEXCEPT;
2598
2599 LocalizedNumberFormatter(const impl::MacroProps ¯os, const Locale &locale);
2600
2601 LocalizedNumberFormatter(impl::MacroProps &¯os, const Locale &locale);
2602
2603 void resetCompiled();
2604
2605 void lnfMoveHelper(LocalizedNumberFormatter&& src);
2606
2607 void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status);
2608
2609 /**
2610 * @return true if the compiled formatter is available.
2611 */
2612 bool computeCompiled(UErrorCode& status) const;
2613
2614 // To give the fluent setters access to this class's constructor:
2615 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
2616 friend class NumberFormatterSettings<LocalizedNumberFormatter>;
2617
2618 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor:
2619 friend class UnlocalizedNumberFormatter;
2620 };
2621
2622 #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
2623 // Warning 4661.
2624 #pragma warning(pop)
2625 #endif
2626
2627 /**
2628 * The result of a number formatting operation. This class allows the result to be exported in several data types,
2629 * including a UnicodeString and a FieldPositionIterator.
2630 *
2631 * Instances of this class are immutable and thread-safe.
2632 *
2633 * @stable ICU 60
2634 */
2635 class U_I18N_API FormattedNumber : public UMemory, public FormattedValue {
2636 public:
2637
2638 /**
2639 * Default constructor; makes an empty FormattedNumber.
2640 * @stable ICU 64
2641 */
FormattedNumber()2642 FormattedNumber()
2643 : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {}
2644
2645 /**
2646 * Move constructor: Leaves the source FormattedNumber in an undefined state.
2647 * @stable ICU 62
2648 */
2649 FormattedNumber(FormattedNumber&& src) U_NOEXCEPT;
2650
2651 /**
2652 * Destruct an instance of FormattedNumber.
2653 * @stable ICU 60
2654 */
2655 virtual ~FormattedNumber() U_OVERRIDE;
2656
2657 /** Copying not supported; use move constructor instead. */
2658 FormattedNumber(const FormattedNumber&) = delete;
2659
2660 /** Copying not supported; use move assignment instead. */
2661 FormattedNumber& operator=(const FormattedNumber&) = delete;
2662
2663 /**
2664 * Move assignment: Leaves the source FormattedNumber in an undefined state.
2665 * @stable ICU 62
2666 */
2667 FormattedNumber& operator=(FormattedNumber&& src) U_NOEXCEPT;
2668
2669 // Copybrief: this method is older than the parent method
2670 /**
2671 * @copybrief FormattedValue::toString()
2672 *
2673 * For more information, see FormattedValue::toString()
2674 *
2675 * @stable ICU 62
2676 */
2677 UnicodeString toString(UErrorCode& status) const U_OVERRIDE;
2678
2679 // Copydoc: this method is new in ICU 64
2680 /** @copydoc FormattedValue::toTempString() */
2681 UnicodeString toTempString(UErrorCode& status) const U_OVERRIDE;
2682
2683 // Copybrief: this method is older than the parent method
2684 /**
2685 * @copybrief FormattedValue::appendTo()
2686 *
2687 * For more information, see FormattedValue::appendTo()
2688 *
2689 * @stable ICU 62
2690 */
2691 Appendable &appendTo(Appendable& appendable, UErrorCode& status) const U_OVERRIDE;
2692
2693 // Copydoc: this method is new in ICU 64
2694 /** @copydoc FormattedValue::nextPosition() */
2695 UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const U_OVERRIDE;
2696
2697 /**
2698 * Export the formatted number as a "numeric string" conforming to the
2699 * syntax defined in the Decimal Arithmetic Specification, available at
2700 * http://speleotrove.com/decimal
2701 *
2702 * This endpoint is useful for obtaining the exact number being printed
2703 * after scaling and rounding have been applied by the number formatter.
2704 *
2705 * Example call site:
2706 *
2707 * auto decimalNumber = fn.toDecimalNumber<std::string>(status);
2708 *
2709 * @tparam StringClass A string class compatible with StringByteSink;
2710 * for example, std::string.
2711 * @param status Set if an error occurs.
2712 * @return A StringClass containing the numeric string.
2713 * @stable ICU 65
2714 */
2715 template<typename StringClass>
2716 inline StringClass toDecimalNumber(UErrorCode& status) const;
2717
2718 #ifndef U_HIDE_DRAFT_API
2719 /**
2720 * Gets the resolved output unit.
2721 *
2722 * The output unit is dependent upon the localized preferences for the usage
2723 * specified via NumberFormatterSettings::usage(), and may be a unit with
2724 * UMEASURE_UNIT_MIXED unit complexity (MeasureUnit::getComplexity()), such
2725 * as "foot-and-inch" or "hour-and-minute-and-second".
2726 *
2727 * @return `MeasureUnit`.
2728 * @draft ICU 68
2729 */
2730 MeasureUnit getOutputUnit(UErrorCode& status) const;
2731
2732 /**
2733 * Gets the gender of the formatted output. Returns "" when the gender is
2734 * unknown, or for ungendered languages.
2735 *
2736 * @internal ICU 69 technology preview.
2737 */
2738 const char *getGender(UErrorCode& status) const;
2739 #endif // U_HIDE_DRAFT_API
2740
2741 #ifndef U_HIDE_INTERNAL_API
2742
2743 /**
2744 * Gets the raw DecimalQuantity for plural rule selection.
2745 * @internal
2746 */
2747 void getDecimalQuantity(impl::DecimalQuantity& output, UErrorCode& status) const;
2748
2749 /**
2750 * Populates the mutable builder type FieldPositionIteratorHandler.
2751 * @internal
2752 */
2753 void getAllFieldPositionsImpl(FieldPositionIteratorHandler& fpih, UErrorCode& status) const;
2754
2755 #endif /* U_HIDE_INTERNAL_API */
2756
2757 private:
2758 // Can't use LocalPointer because UFormattedNumberData is forward-declared
2759 const impl::UFormattedNumberData *fData;
2760
2761 // Error code for the terminal methods
2762 UErrorCode fErrorCode;
2763
2764 /**
2765 * Internal constructor from data type. Adopts the data pointer.
2766 * @internal (private)
2767 */
FormattedNumber(impl::UFormattedNumberData * results)2768 explicit FormattedNumber(impl::UFormattedNumberData *results)
2769 : fData(results), fErrorCode(U_ZERO_ERROR) {}
2770
FormattedNumber(UErrorCode errorCode)2771 explicit FormattedNumber(UErrorCode errorCode)
2772 : fData(nullptr), fErrorCode(errorCode) {}
2773
2774 void toDecimalNumber(ByteSink& sink, UErrorCode& status) const;
2775
2776 // To give LocalizedNumberFormatter format methods access to this class's constructor:
2777 friend class LocalizedNumberFormatter;
2778
2779 // To give C API access to internals
2780 friend struct impl::UFormattedNumberImpl;
2781 };
2782
2783 template<typename StringClass>
toDecimalNumber(UErrorCode & status)2784 StringClass FormattedNumber::toDecimalNumber(UErrorCode& status) const {
2785 StringClass result;
2786 StringByteSink<StringClass> sink(&result);
2787 toDecimalNumber(sink, status);
2788 return result;
2789 }
2790
2791 /**
2792 * See the main description in numberformatter.h for documentation and examples.
2793 *
2794 * @stable ICU 60
2795 */
2796 class U_I18N_API NumberFormatter final {
2797 public:
2798 /**
2799 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at
2800 * the call site.
2801 *
2802 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining.
2803 * @stable ICU 60
2804 */
2805 static UnlocalizedNumberFormatter with();
2806
2807 /**
2808 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call
2809 * site.
2810 *
2811 * @param locale
2812 * The locale from which to load formats and symbols for number formatting.
2813 * @return A {@link LocalizedNumberFormatter}, to be used for chaining.
2814 * @stable ICU 60
2815 */
2816 static LocalizedNumberFormatter withLocale(const Locale &locale);
2817
2818 /**
2819 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
2820 * on a given number skeleton string.
2821 *
2822 * It is possible for an error to occur while parsing. See the overload of this method if you are
2823 * interested in the location of a possible parse error.
2824 *
2825 * For more information on number skeleton strings, see:
2826 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
2827 *
2828 * @param skeleton
2829 * The skeleton string off of which to base this NumberFormatter.
2830 * @param status
2831 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
2832 * @return An UnlocalizedNumberFormatter, to be used for chaining.
2833 * @stable ICU 62
2834 */
2835 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status);
2836
2837 /**
2838 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
2839 * on a given number skeleton string.
2840 *
2841 * If an error occurs while parsing the skeleton string, the offset into the skeleton string at
2842 * which the error occurred will be saved into the UParseError, if provided.
2843 *
2844 * For more information on number skeleton strings, see:
2845 * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
2846 *
2847 * @param skeleton
2848 * The skeleton string off of which to base this NumberFormatter.
2849 * @param perror
2850 * A parse error struct populated if an error occurs when parsing.
2851 * If no error occurs, perror.offset will be set to -1.
2852 * @param status
2853 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
2854 * @return An UnlocalizedNumberFormatter, to be used for chaining.
2855 * @stable ICU 64
2856 */
2857 static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton,
2858 UParseError& perror, UErrorCode& status);
2859
2860 /**
2861 * Use factory methods instead of the constructor to create a NumberFormatter.
2862 */
2863 NumberFormatter() = delete;
2864 };
2865
2866 } // namespace number
2867 U_NAMESPACE_END
2868
2869 #endif /* #if !UCONFIG_NO_FORMATTING */
2870
2871 #endif /* U_SHOW_CPLUSPLUS_API */
2872
2873 #endif // __NUMBERFORMATTER_H__
2874