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