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