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