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