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