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