1 // © 2017 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 #include "unicode/utypes.h"
6 #if !UCONFIG_NO_FORMATTING
7 #ifndef __NUMBERFORMATTER_H__
8 #define __NUMBERFORMATTER_H__
10 #include "unicode/appendable.h"
11 #include "unicode/dcfmtsym.h"
12 #include "unicode/currunit.h"
13 #include "unicode/fieldpos.h"
14 #include "unicode/formattedvalue.h"
15 #include "unicode/fpositer.h"
16 #include "unicode/measunit.h"
17 #include "unicode/nounit.h"
18 #include "unicode/parseerr.h"
19 #include "unicode/plurrule.h"
20 #include "unicode/ucurr.h"
21 #include "unicode/unum.h"
22 #include "unicode/unumberformatter.h"
23 #include "unicode/uobject.h"
25 #ifndef U_HIDE_DRAFT_API
29 * \brief C++ API: Library for localized number formatting introduced in ICU 60.
31 * This library was introduced in ICU 60 to simplify the process of formatting localized number strings.
32 * Basic usage examples:
35 * // Most basic usage:
36 * NumberFormatter::withLocale(...).format(123).toString(); // 1,234 in en-US
38 * // Custom notation, unit, and rounding precision:
39 * NumberFormatter::with()
40 * .notation(Notation::compactShort())
41 * .unit(CurrencyUnit("EUR", status))
42 * .precision(Precision::maxDigits(2))
45 * .toString(); // €1.2K in en-US
47 * // Create a formatter in a singleton by value for use later:
48 * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...)
49 * .unit(NoUnit::percent())
50 * .precision(Precision::fixedFraction(3));
51 * formatter.format(5.9831).toString(); // 5.983% in en-US
53 * // Create a "template" in a singleton unique_ptr but without setting a locale until the call site:
54 * std::unique_ptr<UnlocalizedNumberFormatter> template = NumberFormatter::with()
55 * .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
56 * .unit(MeasureUnit::getMeter())
57 * .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
59 * template->locale(...).format(1234).toString(); // +1,234 meters in en-US
63 * This API offers more features than DecimalFormat and is geared toward new users of ICU.
66 * NumberFormatter instances (i.e., LocalizedNumberFormatter and UnlocalizedNumberFormatter)
67 * are immutable and thread safe. This means that invoking a configuration method has no
68 * effect on the receiving instance; you must store and use the new number formatter instance it returns instead.
71 * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific());
72 * formatter.precision(Precision.maxFraction(2)); // does nothing!
73 * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0"
77 * This API is based on the <em>fluent</em> design pattern popularized by libraries such as Google's Guava. For
78 * extensive details on the design of this API, read <a href="https://goo.gl/szi5VB">the design doc</a>.
85 // Forward declarations:
87 class FieldPositionIteratorHandler
;
92 // Forward declarations:
93 class NumberParserImpl
;
94 class MultiplierParseHandler
;
99 namespace number
{ // icu::number
101 // Forward declarations:
102 class UnlocalizedNumberFormatter
;
103 class LocalizedNumberFormatter
;
104 class FormattedNumber
;
106 class ScientificNotation
;
108 class FractionPrecision
;
109 class CurrencyPrecision
;
110 class IncrementPrecision
;
115 // can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes
117 * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig.
121 typedef int16_t digits_t
;
123 // can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization
125 * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built
126 * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path.
130 static constexpr int32_t kInternalDefaultThreshold
= 3;
132 // Forward declarations:
136 class DecimalQuantity
;
137 class UFormattedNumberData
;
138 class NumberFormatterImpl
;
139 struct ParsedPatternInfo
;
140 class ScientificModifier
;
141 class MultiplierProducer
;
143 class ScientificHandler
;
145 class NumberStringBuilder
;
146 class AffixPatternProvider
;
147 class NumberPropertyMapper
;
148 struct DecimalFormatProperties
;
149 class MultiplierFormatHandler
;
150 class CurrencySymbols
;
151 class GeneratorHelpers
;
153 class NumberRangeFormatterImpl
;
154 struct RangeMacroProps
;
155 struct UFormattedNumberImpl
;
158 * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp.
159 * Declared here so it can be friended.
163 void touchRangeLocales(impl::RangeMacroProps
& macros
);
168 * Extra name reserved in case it is needed in the future.
172 typedef Notation CompactNotation
;
175 * Extra name reserved in case it is needed in the future.
179 typedef Notation SimpleNotation
;
182 * A class that defines the notation style to be used when formatting numbers in NumberFormatter.
186 class U_I18N_API Notation
: public UMemory
{
189 * Print the number using scientific notation (also known as scientific form, standard index form, or standard form
190 * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the
191 * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more
192 * digits after the decimal separator, and the corresponding power of 10 displayed after the "E".
195 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
209 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
212 static ScientificNotation
scientific();
215 * Print the number using engineering notation, a variant of scientific notation in which the exponent must be
219 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
233 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
236 static ScientificNotation
engineering();
239 * Print the number using short-form compact notation.
242 * <em>Compact notation</em>, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with
243 * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to
244 * engineering notation in how it scales numbers.
247 * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing
248 * screen real estate.
251 * In short form, the powers of ten are abbreviated. In <em>en-US</em>, the abbreviations are "K" for thousands, "M"
252 * for millions, "B" for billions, and "T" for trillions. Example outputs in <em>en-US</em> when printing 8.765E7
267 * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest
268 * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal
269 * separator if there is only one digit before the decimal separator. The default compact notation rounding precision
273 * Precision::integer().withMinDigits(2)
276 * @return A CompactNotation for passing to the NumberFormatter notation() setter.
279 static CompactNotation
compactShort();
282 * Print the number using long-form compact notation. For more information on compact notation, see
283 * {@link #compactShort}.
286 * In long form, the powers of ten are spelled out fully. Example outputs in <em>en-US</em> when printing 8.765E7
300 * @return A CompactNotation for passing to the NumberFormatter notation() setter.
303 static CompactNotation
compactLong();
306 * Print the number using simple notation without any scaling by powers of ten. This is the default behavior.
309 * Since this is the default behavior, this method needs to be called only when it is necessary to override a
313 * Example outputs in <em>en-US</em> when printing 8.765E7 through 8.765E0:
326 * @return A SimpleNotation for passing to the NumberFormatter notation() setter.
329 static SimpleNotation
simple();
333 NTN_SCIENTIFIC
, NTN_COMPACT
, NTN_SIMPLE
, NTN_ERROR
336 union NotationUnion
{
337 // For NTN_SCIENTIFIC
339 struct ScientificSettings
{
341 int8_t fEngineeringInterval
;
345 impl::digits_t fMinExponentDigits
;
347 UNumberSignDisplay fExponentSignDisplay
;
351 UNumberCompactStyle compactStyle
;
354 UErrorCode errorCode
;
357 typedef NotationUnion::ScientificSettings ScientificSettings
;
359 Notation(const NotationType
&type
, const NotationUnion
&union_
) : fType(type
), fUnion(union_
) {}
361 Notation(UErrorCode errorCode
) : fType(NTN_ERROR
) {
362 fUnion
.errorCode
= errorCode
;
365 Notation() : fType(NTN_SIMPLE
), fUnion() {}
367 UBool
copyErrorTo(UErrorCode
&status
) const {
368 if (fType
== NTN_ERROR
) {
369 status
= fUnion
.errorCode
;
375 // To allow MacroProps to initialize empty instances:
376 friend struct impl::MacroProps
;
377 friend class ScientificNotation
;
379 // To allow implementation to access internal types:
380 friend class impl::NumberFormatterImpl
;
381 friend class impl::ScientificModifier
;
382 friend class impl::ScientificHandler
;
384 // To allow access to the skeleton generation code:
385 friend class impl::GeneratorHelpers
;
389 * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter.
392 * To create a ScientificNotation, use one of the factory methods in {@link Notation}.
396 class U_I18N_API ScientificNotation
: public Notation
{
399 * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if
400 * necessary. Useful for fixed-width display.
403 * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in <em>en-US</em> instead of
404 * the default "1.23E2".
406 * @param minExponentDigits
407 * The minimum number of digits to show in the exponent.
408 * @return A ScientificNotation, for chaining.
411 ScientificNotation
withMinExponentDigits(int32_t minExponentDigits
) const;
414 * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO,
415 * showing the minus sign but not the plus sign.
418 * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in <em>en-US</em>
419 * instead of the default "1.23E2".
421 * @param exponentSignDisplay
422 * The strategy for displaying the sign in the exponent.
423 * @return A ScientificNotation, for chaining.
426 ScientificNotation
withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay
) const;
429 // Inherit constructor
430 using Notation::Notation
;
432 // Raw constructor for NumberPropertyMapper
433 ScientificNotation(int8_t fEngineeringInterval
, bool fRequireMinInt
, impl::digits_t fMinExponentDigits
,
434 UNumberSignDisplay fExponentSignDisplay
);
436 friend class Notation
;
438 // So that NumberPropertyMapper can create instances
439 friend class impl::NumberPropertyMapper
;
443 * Extra name reserved in case it is needed in the future.
447 typedef Precision SignificantDigitsPrecision
;
450 * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter.
453 * To create a Precision, use one of the factory methods.
457 class U_I18N_API Precision
: public UMemory
{
461 * Show all available digits to full precision.
464 * <strong>NOTE:</strong> When formatting a <em>double</em>, this method, along with {@link #minFraction} and
465 * {@link #minSignificantDigits}, will trigger complex algorithm similar to <em>Dragon4</em> to determine the
466 * low-order digits and the number of digits to display based on the value of the double.
467 * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction}
468 * or {@link #maxSignificantDigits} instead to maximize performance.
469 * For more information, read the following blog post.
472 * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/
474 * @return A Precision for chaining or passing to the NumberFormatter precision() setter.
477 static Precision
unlimited();
480 * Show numbers rounded if necessary to the nearest integer.
482 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
485 static FractionPrecision
integer();
488 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
489 * Additionally, pad with zeros to ensure that this number of places are always shown.
492 * Example output with minMaxFractionPlaces = 3:
506 * This method is equivalent to {@link #minMaxFraction} with both arguments equal.
508 * @param minMaxFractionPlaces
509 * The minimum and maximum number of numerals to display after the decimal separator (rounding if too
510 * long or padding with zeros if too short).
511 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
514 static FractionPrecision
fixedFraction(int32_t minMaxFractionPlaces
);
517 * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if
518 * necessary. Do not perform rounding (display numbers to their full precision).
521 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
523 * @param minFractionPlaces
524 * The minimum number of numerals to display after the decimal separator (padding with zeros if
526 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
529 static FractionPrecision
minFraction(int32_t minFractionPlaces
);
532 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
533 * Unlike the other fraction rounding strategies, this strategy does <em>not</em> pad zeros to the end of the
536 * @param maxFractionPlaces
537 * The maximum number of numerals to display after the decimal mark (rounding if necessary).
538 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
541 static FractionPrecision
maxFraction(int32_t maxFractionPlaces
);
544 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator);
545 * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if
548 * @param minFractionPlaces
549 * The minimum number of numerals to display after the decimal separator (padding with zeros if
551 * @param maxFractionPlaces
552 * The maximum number of numerals to display after the decimal separator (rounding if necessary).
553 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
556 static FractionPrecision
minMaxFraction(int32_t minFractionPlaces
, int32_t maxFractionPlaces
);
559 * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally,
560 * pad with zeros to ensure that this number of significant digits/figures are always shown.
563 * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal.
565 * @param minMaxSignificantDigits
566 * The minimum and maximum number of significant digits to display (rounding if too long or padding with
567 * zeros if too short).
568 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
571 static SignificantDigitsPrecision
fixedSignificantDigits(int32_t minMaxSignificantDigits
);
574 * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not
575 * perform rounding (display numbers to their full precision).
578 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
580 * @param minSignificantDigits
581 * The minimum number of significant digits to display (padding with zeros if too short).
582 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
585 static SignificantDigitsPrecision
minSignificantDigits(int32_t minSignificantDigits
);
588 * Show numbers rounded if necessary to a certain number of significant digits/figures.
590 * @param maxSignificantDigits
591 * The maximum number of significant digits to display (rounding if too long).
592 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
595 static SignificantDigitsPrecision
maxSignificantDigits(int32_t maxSignificantDigits
);
598 * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at
599 * least a certain number of significant digits, padding with zeros if necessary.
601 * @param minSignificantDigits
602 * The minimum number of significant digits to display (padding with zeros if necessary).
603 * @param maxSignificantDigits
604 * The maximum number of significant digits to display (rounding if necessary).
605 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
608 static SignificantDigitsPrecision
minMaxSignificantDigits(int32_t minSignificantDigits
,
609 int32_t maxSignificantDigits
);
612 * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the
613 * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5.
616 * In order to ensure that numbers are padded to the appropriate number of fraction places, call
617 * withMinFraction() on the return value of this method.
618 * For example, to round to the nearest 0.5 and always display 2 numerals after the
619 * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run:
622 * Precision::increment(0.5).withMinFraction(2)
625 * @param roundingIncrement
626 * The increment to which to round numbers.
627 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
630 static IncrementPrecision
increment(double roundingIncrement
);
633 * Show numbers rounded and padded according to the rules for the currency unit. The most common
634 * rounding precision settings for currencies include <code>Precision::fixedFraction(2)</code>,
635 * <code>Precision::integer()</code>, and <code>Precision::increment(0.05)</code> for cash transactions
636 * ("nickel rounding").
639 * The exact rounding details will be resolved at runtime based on the currency unit specified in the
640 * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another
641 * currency, the withCurrency() method can be called on the return value of this method.
643 * @param currencyUsage
644 * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may
645 * be limited by the available denominations of cash or coins).
646 * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter.
649 static CurrencyPrecision
currency(UCurrencyUsage currencyUsage
);
657 RND_FRACTION_SIGNIFICANT
,
659 // Used for strange increments like 3.14.
662 // Used for increments with 1 as the only digit. This is different than fraction
663 // rounding because it supports having additional trailing zeros. For example, this
664 // class is used to round with the increment 0.010.
667 // Used for increments with 5 as the only digit (nickel rounding).
671 RND_INCREMENT_SIGNIFICANT
, // Apple addition rdar://52538227
675 union PrecisionUnion
{
677 struct FractionSignificantSettings
{
678 // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT
680 impl::digits_t fMinFrac
;
682 impl::digits_t fMaxFrac
;
684 impl::digits_t fMinSig
;
686 impl::digits_t fMaxSig
;
689 struct IncrementSettings
{
690 // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE
694 impl::digits_t fMinFrac
;
696 impl::digits_t fMaxFrac
;
699 struct IncrementSignificantSettings
{ // Apple addition rdar://52538227
700 // For // Apple addition rdar://52538227
704 impl::digits_t fMinSig
;
706 impl::digits_t fMaxSig
;
708 UCurrencyUsage currencyUsage
; // For RND_CURRENCY
709 UErrorCode errorCode
; // For RND_ERROR
712 typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings
;
713 typedef PrecisionUnion::IncrementSettings IncrementSettings
;
714 typedef PrecisionUnion::IncrementSignificantSettings IncrementSignificantSettings
;
716 /** The Precision encapsulates the RoundingMode when used within the implementation. */
717 UNumberFormatRoundingMode fRoundingMode
;
719 Precision(const PrecisionType
& type
, const PrecisionUnion
& union_
,
720 UNumberFormatRoundingMode roundingMode
)
721 : fType(type
), fUnion(union_
), fRoundingMode(roundingMode
) {}
723 Precision(UErrorCode errorCode
) : fType(RND_ERROR
) {
724 fUnion
.errorCode
= errorCode
;
727 Precision() : fType(RND_BOGUS
) {}
729 bool isBogus() const {
730 return fType
== RND_BOGUS
;
733 UBool
copyErrorTo(UErrorCode
&status
) const {
734 if (fType
== RND_ERROR
) {
735 status
= fUnion
.errorCode
;
741 // On the parent type so that this method can be called internally on Precision instances.
742 Precision
withCurrency(const CurrencyUnit
¤cy
, UErrorCode
&status
) const;
744 static FractionPrecision
constructFraction(int32_t minFrac
, int32_t maxFrac
);
746 static Precision
constructSignificant(int32_t minSig
, int32_t maxSig
);
748 static Precision
constructIncrementSignificant(double increment
, int32_t minSig
, int32_t maxSig
); // Apple
751 constructFractionSignificant(const FractionPrecision
&base
, int32_t minSig
, int32_t maxSig
);
753 static IncrementPrecision
constructIncrement(double increment
, int32_t minFrac
);
755 static CurrencyPrecision
constructCurrency(UCurrencyUsage usage
);
757 static Precision
constructPassThrough();
759 // To allow MacroProps/MicroProps to initialize bogus instances:
760 friend struct impl::MacroProps
;
761 friend struct impl::MicroProps
;
763 // To allow NumberFormatterImpl to access isBogus() and other internal methods:
764 friend class impl::NumberFormatterImpl
;
766 // To allow NumberPropertyMapper to create instances from DecimalFormatProperties:
767 friend class impl::NumberPropertyMapper
;
769 // To allow access to the main implementation class:
770 friend class impl::RoundingImpl
;
772 // To allow child classes to call private methods:
773 friend class FractionPrecision
;
774 friend class CurrencyPrecision
;
775 friend class IncrementPrecision
;
777 // To allow access to the skeleton generation code:
778 friend class impl::GeneratorHelpers
;
782 * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be
783 * used when formatting numbers in NumberFormatter.
786 * To create a FractionPrecision, use one of the factory methods on Precision.
790 class U_I18N_API FractionPrecision
: public Precision
{
793 * Ensure that no less than this number of significant digits are retained when rounding according to fraction
797 * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum figures set to 2, 3.141
798 * becomes "3.1" instead.
801 * This setting does not affect the number of trailing zeros. For example, 3.01 would print as "3", not "3.0".
803 * @param minSignificantDigits
804 * The number of significant figures to guarantee.
805 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
808 Precision
withMinDigits(int32_t minSignificantDigits
) const;
811 * Ensure that no more than this number of significant digits are retained when rounding according to fraction
815 * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum figures set to 2, 123.4
816 * becomes "120" instead.
819 * This setting does not affect the number of trailing zeros. For example, with fixed fraction of 2, 123.4 would
822 * @param maxSignificantDigits
823 * Round the number to no more than this number of significant figures.
824 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
827 Precision
withMaxDigits(int32_t maxSignificantDigits
) const;
830 // Inherit constructor
831 using Precision::Precision
;
833 // To allow parent class to call this class's constructor:
834 friend class Precision
;
838 * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in
842 * To create a CurrencyPrecision, use one of the factory methods on Precision.
846 class U_I18N_API CurrencyPrecision
: public Precision
{
849 * Associates a currency with this rounding precision.
852 * <strong>Calling this method is <em>not required</em></strong>, because the currency specified in unit()
853 * is automatically applied to currency rounding precisions. However,
854 * this method enables you to override that automatic association.
857 * This method also enables numbers to be formatted using currency rounding rules without explicitly using a
861 * The currency to associate with this rounding precision.
862 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
865 Precision
withCurrency(const CurrencyUnit
¤cy
) const;
868 // Inherit constructor
869 using Precision::Precision
;
871 // To allow parent class to call this class's constructor:
872 friend class Precision
;
876 * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in
880 * To create an IncrementPrecision, use one of the factory methods on Precision.
884 class U_I18N_API IncrementPrecision
: public Precision
{
887 * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if
888 * necessary. By default, no trailing zeros are added.
891 * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00",
892 * "0.50", "1.00", and "1.50".
895 * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment.
897 * @param minFrac The minimum number of digits after the decimal separator.
898 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
901 Precision
withMinFraction(int32_t minFrac
) const;
904 // Inherit constructor
905 using Precision::Precision
;
907 // To allow parent class to call this class's constructor:
908 friend class Precision
;
912 * A class that defines the strategy for padding and truncating integers before the decimal separator.
915 * To create an IntegerWidth, use one of the factory methods.
918 * @see NumberFormatter
920 class U_I18N_API IntegerWidth
: public UMemory
{
923 * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator.
926 * For example, with minInt=3, the number 55 will get printed as "055".
929 * The minimum number of places before the decimal separator.
930 * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter.
933 static IntegerWidth
zeroFillTo(int32_t minInt
);
936 * Truncate numbers exceeding a certain number of numerals before the decimal separator.
938 * For example, with maxInt=3, the number 1234 will get printed as "234".
941 * The maximum number of places before the decimal separator. maxInt == -1 means no
943 * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter.
946 IntegerWidth
truncateAt(int32_t maxInt
);
951 impl::digits_t fMinInt
;
952 impl::digits_t fMaxInt
;
953 bool fFormatFailIfMoreThanMaxDigits
;
955 UErrorCode errorCode
;
957 bool fHasError
= false;
959 IntegerWidth(impl::digits_t minInt
, impl::digits_t maxInt
, bool formatFailIfMoreThanMaxDigits
);
961 IntegerWidth(UErrorCode errorCode
) { // NOLINT
962 fUnion
.errorCode
= errorCode
;
966 IntegerWidth() { // NOLINT
967 fUnion
.minMaxInt
.fMinInt
= -1;
970 /** Returns the default instance. */
971 static IntegerWidth
standard() {
972 return IntegerWidth::zeroFillTo(1);
975 bool isBogus() const {
976 return !fHasError
&& fUnion
.minMaxInt
.fMinInt
== -1;
979 UBool
copyErrorTo(UErrorCode
&status
) const {
981 status
= fUnion
.errorCode
;
987 void apply(impl::DecimalQuantity
&quantity
, UErrorCode
&status
) const;
989 bool operator==(const IntegerWidth
& other
) const;
991 // To allow MacroProps/MicroProps to initialize empty instances:
992 friend struct impl::MacroProps
;
993 friend struct impl::MicroProps
;
995 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
996 friend class impl::NumberFormatterImpl
;
998 // So that NumberPropertyMapper can create instances
999 friend class impl::NumberPropertyMapper
;
1001 // To allow access to the skeleton generation code:
1002 friend class impl::GeneratorHelpers
;
1006 * A class that defines a quantity by which a number should be multiplied when formatting.
1009 * To create a Scale, use one of the factory methods.
1013 class U_I18N_API Scale
: public UMemory
{
1016 * Do not change the value of numbers when formatting or parsing.
1018 * @return A Scale to prevent any multiplication.
1021 static Scale
none();
1024 * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit:
1027 * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2))
1030 * @return A Scale for passing to the setter in NumberFormatter.
1033 static Scale
powerOfTen(int32_t power
);
1036 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
1038 * This method takes a string in a decimal number format with syntax
1039 * as defined in the Decimal Arithmetic Specification, available at
1040 * http://speleotrove.com/decimal
1042 * Also see the version of this method that takes a double.
1044 * @return A Scale for passing to the setter in NumberFormatter.
1047 static Scale
byDecimal(StringPiece multiplicand
);
1050 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
1052 * This method takes a double; also see the version of this method that takes an exact decimal.
1054 * @return A Scale for passing to the setter in NumberFormatter.
1057 static Scale
byDouble(double multiplicand
);
1060 * Multiply a number by both a power of ten and by an arbitrary double value.
1062 * @return A Scale for passing to the setter in NumberFormatter.
1065 static Scale
byDoubleAndPowerOfTen(double multiplicand
, int32_t power
);
1067 // We need a custom destructor for the DecNum, which means we need to declare
1068 // the copy/move constructor/assignment quartet.
1070 /** @draft ICU 62 */
1071 Scale(const Scale
& other
);
1073 /** @draft ICU 62 */
1074 Scale
& operator=(const Scale
& other
);
1076 /** @draft ICU 62 */
1077 Scale(Scale
&& src
) U_NOEXCEPT
;
1079 /** @draft ICU 62 */
1080 Scale
& operator=(Scale
&& src
) U_NOEXCEPT
;
1082 /** @draft ICU 62 */
1085 #ifndef U_HIDE_INTERNAL_API
1087 Scale(int32_t magnitude
, impl::DecNum
* arbitraryToAdopt
);
1088 #endif /* U_HIDE_INTERNAL_API */
1092 impl::DecNum
* fArbitrary
;
1095 Scale(UErrorCode error
) : fMagnitude(0), fArbitrary(nullptr), fError(error
) {}
1097 Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR
) {}
1099 bool isValid() const {
1100 return fMagnitude
!= 0 || fArbitrary
!= nullptr;
1103 UBool
copyErrorTo(UErrorCode
&status
) const {
1104 if (fError
!= U_ZERO_ERROR
) {
1111 void applyTo(impl::DecimalQuantity
& quantity
) const;
1113 void applyReciprocalTo(impl::DecimalQuantity
& quantity
) const;
1115 // To allow MacroProps/MicroProps to initialize empty instances:
1116 friend struct impl::MacroProps
;
1117 friend struct impl::MicroProps
;
1119 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1120 friend class impl::NumberFormatterImpl
;
1122 // To allow the helper class MultiplierFormatHandler access to private fields:
1123 friend class impl::MultiplierFormatHandler
;
1125 // To allow access to the skeleton generation code:
1126 friend class impl::GeneratorHelpers
;
1128 // To allow access to parsing code:
1129 friend class ::icu::numparse::impl::NumberParserImpl
;
1130 friend class ::icu::numparse::impl::MultiplierParseHandler
;
1135 // Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1137 class U_I18N_API SymbolsWrapper
: public UMemory
{
1140 SymbolsWrapper() : fType(SYMPTR_NONE
), fPtr
{nullptr} {}
1143 SymbolsWrapper(const SymbolsWrapper
&other
);
1146 SymbolsWrapper
&operator=(const SymbolsWrapper
&other
);
1149 SymbolsWrapper(SymbolsWrapper
&& src
) U_NOEXCEPT
;
1152 SymbolsWrapper
&operator=(SymbolsWrapper
&& src
) U_NOEXCEPT
;
1157 #ifndef U_HIDE_INTERNAL_API
1160 * Set whether DecimalFormatSymbols copy is deep (clone)
1161 * or shallow (pointer copy). Apple <rdar://problem/49955427>
1164 void setDFSShallowCopy(UBool shallow
);
1167 * The provided object is copied, but we do not adopt it.
1170 void setTo(const DecimalFormatSymbols
&dfs
);
1173 * Adopt the provided object.
1176 void setTo(const NumberingSystem
*ns
);
1179 * Whether the object is currently holding a DecimalFormatSymbols.
1182 bool isDecimalFormatSymbols() const;
1185 * Whether the object is currently holding a NumberingSystem.
1188 bool isNumberingSystem() const;
1191 * Get the DecimalFormatSymbols pointer. No ownership change.
1194 const DecimalFormatSymbols
*getDecimalFormatSymbols() const;
1197 * Get the NumberingSystem pointer. No ownership change.
1200 const NumberingSystem
*getNumberingSystem() const;
1202 #endif // U_HIDE_INTERNAL_API
1205 UBool
copyErrorTo(UErrorCode
&status
) const {
1206 if ((fType
== SYMPTR_DFS
|| fType
== SYMPTR_DFS_SHALLOWCOPY
) && fPtr
.dfs
== nullptr) {
1207 status
= U_MEMORY_ALLOCATION_ERROR
;
1209 } else if (fType
== SYMPTR_NS
&& fPtr
.ns
== nullptr) {
1210 status
= U_MEMORY_ALLOCATION_ERROR
;
1217 enum SymbolsPointerType
{
1218 SYMPTR_NONE
, SYMPTR_DFS
, SYMPTR_NS
, SYMPTR_DFS_SHALLOWCOPY
// Apple <rdar://problem/49955427> add SHALLOWCOPY
1222 const DecimalFormatSymbols
*dfs
;
1223 const NumberingSystem
*ns
;
1226 void doCopyFrom(const SymbolsWrapper
&other
);
1228 void doMoveFrom(SymbolsWrapper
&& src
);
1233 // Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1235 class U_I18N_API Grouper
: public UMemory
{
1237 #ifndef U_HIDE_INTERNAL_API
1239 static Grouper
forStrategy(UNumberGroupingStrategy grouping
);
1242 * Resolve the values in Properties to a Grouper object.
1245 static Grouper
forProperties(const DecimalFormatProperties
& properties
);
1247 // Future: static Grouper forProperties(DecimalFormatProperties& properties);
1250 Grouper(int16_t grouping1
, int16_t grouping2
, int16_t minGrouping
, UNumberGroupingStrategy strategy
)
1251 : fGrouping1(grouping1
),
1252 fGrouping2(grouping2
),
1253 fMinGrouping(minGrouping
),
1254 fStrategy(strategy
) {}
1255 #endif // U_HIDE_INTERNAL_API
1258 int16_t getPrimary() const;
1261 int16_t getSecondary() const;
1265 * The grouping sizes, with the following special values:
1267 * <li>-1 = no grouping
1268 * <li>-2 = needs locale data
1269 * <li>-4 = fall back to Western grouping if not in locale
1276 * The minimum grouping size, with the following special values:
1278 * <li>-2 = needs locale data
1279 * <li>-3 = no less than 2
1282 int16_t fMinGrouping
;
1285 * The UNumberGroupingStrategy that was used to create this Grouper, or UNUM_GROUPING_COUNT if this
1286 * was not created from a UNumberGroupingStrategy.
1288 UNumberGroupingStrategy fStrategy
;
1290 Grouper() : fGrouping1(-3) {}
1292 bool isBogus() const {
1293 return fGrouping1
== -3;
1296 /** NON-CONST: mutates the current instance. */
1297 void setLocaleData(const impl::ParsedPatternInfo
&patternInfo
, const Locale
& locale
);
1299 bool groupAtPosition(int32_t position
, const impl::DecimalQuantity
&value
) const;
1301 // To allow MacroProps/MicroProps to initialize empty instances:
1302 friend struct MacroProps
;
1303 friend struct MicroProps
;
1305 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1306 friend class NumberFormatterImpl
;
1308 // To allow NumberParserImpl to perform setLocaleData():
1309 friend class ::icu::numparse::impl::NumberParserImpl
;
1311 // To allow access to the skeleton generation code:
1312 friend class impl::GeneratorHelpers
;
1315 // Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1317 class U_I18N_API Padder
: public UMemory
{
1319 #ifndef U_HIDE_INTERNAL_API
1321 static Padder
none();
1324 static Padder
codePoints(UChar32 cp
, int32_t targetWidth
, UNumberFormatPadPosition position
);
1325 #endif // U_HIDE_INTERNAL_API
1328 static Padder
forProperties(const DecimalFormatProperties
& properties
);
1331 UChar32 fWidth
; // -3 = error; -2 = bogus; -1 = no padding
1335 UNumberFormatPadPosition fPosition
;
1337 UErrorCode errorCode
;
1340 Padder(UChar32 cp
, int32_t width
, UNumberFormatPadPosition position
);
1342 Padder(int32_t width
);
1344 Padder(UErrorCode errorCode
) : fWidth(-3) { // NOLINT
1345 fUnion
.errorCode
= errorCode
;
1348 Padder() : fWidth(-2) {} // NOLINT
1350 bool isBogus() const {
1351 return fWidth
== -2;
1354 UBool
copyErrorTo(UErrorCode
&status
) const {
1356 status
= fUnion
.errorCode
;
1362 bool isValid() const {
1366 int32_t padAndApply(const impl::Modifier
&mod1
, const impl::Modifier
&mod2
,
1367 impl::NumberStringBuilder
&string
, int32_t leftIndex
, int32_t rightIndex
,
1368 UErrorCode
&status
) const;
1370 // To allow MacroProps/MicroProps to initialize empty instances:
1371 friend struct MacroProps
;
1372 friend struct MicroProps
;
1374 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1375 friend class impl::NumberFormatterImpl
;
1377 // To allow access to the skeleton generation code:
1378 friend class impl::GeneratorHelpers
;
1381 // Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1383 struct U_I18N_API MacroProps
: public UMemory
{
1388 MeasureUnit unit
; // = NoUnit::base();
1391 MeasureUnit perUnit
; // = NoUnit::base();
1394 Precision precision
; // = Precision(); (bogus)
1397 UNumberFormatRoundingMode roundingMode
= UNUM_ROUND_HALFEVEN
;
1400 Grouper grouper
; // = Grouper(); (bogus)
1403 Padder padder
; // = Padder(); (bogus)
1406 IntegerWidth integerWidth
; // = IntegerWidth(); (bogus)
1409 SymbolsWrapper symbols
;
1411 // UNUM_XYZ_COUNT denotes null (bogus) values.
1414 UNumberUnitWidth unitWidth
= UNUM_UNIT_WIDTH_COUNT
;
1417 UNumberSignDisplay sign
= UNUM_SIGN_COUNT
;
1420 UNumberDecimalSeparatorDisplay decimal
= UNUM_DECIMAL_SEPARATOR_COUNT
;
1423 Scale scale
; // = Scale(); (benign value)
1426 const AffixPatternProvider
* affixProvider
= nullptr; // no ownership
1429 const PluralRules
* rules
= nullptr; // no ownership
1432 const CurrencySymbols
* currencySymbols
= nullptr; // no ownership
1435 int32_t threshold
= kInternalDefaultThreshold
;
1437 /** @internal Apple addition for <rdar://problem/39240173> */
1438 bool adjustDoublePrecision
= false;
1443 // NOTE: Uses default copy and move constructors.
1446 * Check all members for errors.
1449 bool copyErrorTo(UErrorCode
&status
) const {
1450 return notation
.copyErrorTo(status
) || precision
.copyErrorTo(status
) ||
1451 padder
.copyErrorTo(status
) || integerWidth
.copyErrorTo(status
) ||
1452 symbols
.copyErrorTo(status
) || scale
.copyErrorTo(status
);
1459 * An abstract base class for specifying settings related to number formatting. This class is implemented by
1460 * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. This class is not intended for
1461 * public subclassing.
1463 template<typename Derived
>
1464 class U_I18N_API NumberFormatterSettings
{
1467 * Specifies the notation style (simple, scientific, or compact) for rendering numbers.
1470 * <li>Simple notation: "12,300"
1471 * <li>Scientific notation: "1.23E4"
1472 * <li>Compact notation: "12K"
1476 * All notation styles will be properly localized with locale data, and all notation styles are compatible with
1477 * units, rounding precisions, and other number formatter settings.
1480 * Pass this method the return value of a {@link Notation} factory method. For example:
1483 * NumberFormatter::with().notation(Notation::compactShort())
1486 * The default is to use simple notation.
1489 * The notation strategy to use.
1490 * @return The fluent chain.
1494 Derived
notation(const Notation
¬ation
) const &;
1497 * Overload of notation() for use on an rvalue reference.
1500 * The notation strategy to use.
1501 * @return The fluent chain.
1505 Derived
notation(const Notation
¬ation
) &&;
1508 * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers.
1511 * <li>Unit of measure: "12.3 meters"
1512 * <li>Currency: "$12.30"
1513 * <li>Percent: "12.3%"
1516 * All units will be properly localized with locale data, and all units are compatible with notation styles,
1517 * rounding precisions, and other number formatter settings.
1519 * Pass this method any instance of {@link MeasureUnit}. For units of measure:
1522 * NumberFormatter::with().unit(MeasureUnit::getMeter())
1528 * NumberFormatter::with().unit(CurrencyUnit(u"USD", status))
1534 * NumberFormatter::with().unit(NoUnit.percent())
1537 * See {@link #perUnit} for information on how to format strings like "5 meters per second".
1539 * The default is to render without units (equivalent to NoUnit.base()).
1542 * The unit to render.
1543 * @return The fluent chain.
1550 Derived
unit(const icu::MeasureUnit
&unit
) const &;
1553 * Overload of unit() for use on an rvalue reference.
1556 * The unit to render.
1557 * @return The fluent chain.
1561 Derived
unit(const icu::MeasureUnit
&unit
) &&;
1564 * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
1565 * methods that return pointers that need ownership.
1567 * Note: consider using the MeasureFormat factory methods that return by value.
1570 * The unit to render.
1571 * @return The fluent chain.
1576 Derived
adoptUnit(icu::MeasureUnit
*unit
) const &;
1579 * Overload of adoptUnit() for use on an rvalue reference.
1582 * The unit to render.
1583 * @return The fluent chain.
1587 Derived
adoptUnit(icu::MeasureUnit
*unit
) &&;
1590 * Sets a unit to be used in the denominator. For example, to format "3 m/s", pass METER to the unit and SECOND to
1593 * Pass this method any instance of {@link MeasureUnit}. Example:
1596 * NumberFormatter::with()
1597 * .unit(MeasureUnit::getMeter())
1598 * .perUnit(MeasureUnit::getSecond())
1601 * The default is not to display any unit in the denominator.
1603 * If a per-unit is specified without a primary unit via {@link #unit}, the behavior is undefined.
1606 * The unit to render in the denominator.
1607 * @return The fluent chain
1611 Derived
perUnit(const icu::MeasureUnit
&perUnit
) const &;
1614 * Overload of perUnit() for use on an rvalue reference.
1617 * The unit to render in the denominator.
1618 * @return The fluent chain.
1622 Derived
perUnit(const icu::MeasureUnit
&perUnit
) &&;
1625 * Like perUnit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
1626 * methods that return pointers that need ownership.
1628 * Note: consider using the MeasureFormat factory methods that return by value.
1631 * The unit to render in the denominator.
1632 * @return The fluent chain.
1637 Derived
adoptPerUnit(icu::MeasureUnit
*perUnit
) const &;
1640 * Overload of adoptPerUnit() for use on an rvalue reference.
1643 * The unit to render in the denominator.
1644 * @return The fluent chain.
1645 * @see #adoptPerUnit
1648 Derived
adoptPerUnit(icu::MeasureUnit
*perUnit
) &&;
1651 * Specifies the rounding precision to use when formatting numbers.
1654 * <li>Round to 3 decimal places: "3.142"
1655 * <li>Round to 3 significant figures: "3.14"
1656 * <li>Round to the closest nickel: "3.15"
1657 * <li>Do not perform rounding: "3.1415926..."
1661 * Pass this method the return value of one of the factory methods on {@link Precision}. For example:
1664 * NumberFormatter::with().precision(Precision::fixedFraction(2))
1668 * In most cases, the default rounding strategy is to round to 6 fraction places; i.e.,
1669 * <code>Precision.maxFraction(6)</code>. The exceptions are if compact notation is being used, then the compact
1670 * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency,
1671 * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for
1675 * The rounding precision to use.
1676 * @return The fluent chain.
1680 Derived
precision(const Precision
& precision
) const &;
1683 * Overload of precision() for use on an rvalue reference.
1686 * The rounding precision to use.
1687 * @return The fluent chain.
1691 Derived
precision(const Precision
& precision
) &&;
1694 * Specifies how to determine the direction to round a number when it has more digits than fit in the
1695 * desired precision. When formatting 1.235:
1698 * <li>Ceiling rounding mode with integer precision: "2"
1699 * <li>Half-down rounding mode with 2 fixed fraction digits: "1.23"
1700 * <li>Half-up rounding mode with 2 fixed fraction digits: "1.24"
1703 * The default is HALF_EVEN. For more information on rounding mode, see the ICU userguide here:
1705 * http://userguide.icu-project.org/formatparse/numbers/rounding-modes
1707 * @param roundingMode The rounding mode to use.
1708 * @return The fluent chain.
1711 Derived
roundingMode(UNumberFormatRoundingMode roundingMode
) const &;
1714 * Overload of roundingMode() for use on an rvalue reference.
1716 * @param roundingMode The rounding mode to use.
1717 * @return The fluent chain.
1718 * @see #roundingMode
1721 Derived
roundingMode(UNumberFormatRoundingMode roundingMode
) &&;
1724 * Specifies the grouping strategy to use when formatting numbers.
1727 * <li>Default grouping: "12,300" and "1,230"
1728 * <li>Grouping with at least 2 digits: "12,300" and "1230"
1729 * <li>No grouping: "12300" and "1230"
1733 * The exact grouping widths will be chosen based on the locale.
1736 * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example:
1739 * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2)
1742 * The default is to perform grouping according to locale data; most locales, but not all locales,
1743 * enable it by default.
1746 * The grouping strategy to use.
1747 * @return The fluent chain.
1750 Derived
grouping(UNumberGroupingStrategy strategy
) const &;
1753 * Overload of grouping() for use on an rvalue reference.
1756 * The grouping strategy to use.
1757 * @return The fluent chain.
1761 Derived
grouping(UNumberGroupingStrategy strategy
) &&;
1764 * Specifies the minimum and maximum number of digits to render before the decimal mark.
1767 * <li>Zero minimum integer digits: ".08"
1768 * <li>One minimum integer digit: "0.08"
1769 * <li>Two minimum integer digits: "00.08"
1773 * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example:
1776 * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2))
1779 * The default is to have one minimum integer digit.
1782 * The integer width to use.
1783 * @return The fluent chain.
1787 Derived
integerWidth(const IntegerWidth
&style
) const &;
1790 * Overload of integerWidth() for use on an rvalue reference.
1793 * The integer width to use.
1794 * @return The fluent chain.
1795 * @see #integerWidth
1798 Derived
integerWidth(const IntegerWidth
&style
) &&;
1801 * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering
1805 * <li><em>en_US</em> symbols: "12,345.67"
1806 * <li><em>fr_FR</em> symbols: "12 345,67"
1807 * <li><em>de_CH</em> symbols: "12’345.67"
1808 * <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇"
1812 * Pass this method an instance of {@link DecimalFormatSymbols}. For example:
1815 * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status))
1819 * <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale.
1820 * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar
1824 * <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object
1825 * after passing it into the fluent chain will not be seen.
1828 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
1829 * or NumberingSystem.
1832 * The default is to choose the symbols based on the locale specified in the fluent chain.
1835 * The DecimalFormatSymbols to use.
1836 * @return The fluent chain.
1837 * @see DecimalFormatSymbols
1840 Derived
symbols(const DecimalFormatSymbols
&symbols
) const &;
1843 * Overload of symbols() for use on an rvalue reference.
1846 * The DecimalFormatSymbols to use.
1847 * @return The fluent chain.
1851 Derived
symbols(const DecimalFormatSymbols
&symbols
) &&;
1854 * Specifies that the given numbering system should be used when fetching symbols.
1857 * <li>Latin numbering system: "12,345"
1858 * <li>Myanmar numbering system: "၁၂,၃၄၅"
1859 * <li>Math Sans Bold numbering system: "𝟭𝟮,𝟯𝟰𝟱"
1863 * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin
1864 * alphabet numbering system (ASCII digits):
1867 * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status))
1871 * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
1872 * or NumberingSystem.
1875 * The default is to choose the best numbering system for the locale.
1878 * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods.
1881 * The NumberingSystem to use.
1882 * @return The fluent chain.
1883 * @see NumberingSystem
1886 Derived
adoptSymbols(NumberingSystem
*symbols
) const &;
1889 * Overload of adoptSymbols() for use on an rvalue reference.
1892 * The NumberingSystem to use.
1893 * @return The fluent chain.
1894 * @see #adoptSymbols
1897 Derived
adoptSymbols(NumberingSystem
*symbols
) &&;
1900 * Sets the width of the unit (measure unit or currency). Most common values:
1903 * <li>Short: "$12.00", "12 m"
1904 * <li>ISO Code: "USD 12.00"
1905 * <li>Full name: "12.00 US dollars", "12 meters"
1909 * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example:
1912 * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
1916 * The default is the SHORT width.
1919 * The width to use when rendering numbers.
1920 * @return The fluent chain
1921 * @see UNumberUnitWidth
1924 Derived
unitWidth(UNumberUnitWidth width
) const &;
1927 * Overload of unitWidth() for use on an rvalue reference.
1930 * The width to use when rendering numbers.
1931 * @return The fluent chain.
1935 Derived
unitWidth(UNumberUnitWidth width
) &&;
1938 * Sets the plus/minus sign display strategy. Most common values:
1941 * <li>Auto: "123", "-123"
1942 * <li>Always: "+123", "-123"
1943 * <li>Accounting: "$123", "($123)"
1947 * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example:
1950 * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
1954 * The default is AUTO sign display.
1957 * The sign display strategy to use when rendering numbers.
1958 * @return The fluent chain
1959 * @see UNumberSignDisplay
1962 Derived
sign(UNumberSignDisplay style
) const &;
1965 * Overload of sign() for use on an rvalue reference.
1968 * The sign display strategy to use when rendering numbers.
1969 * @return The fluent chain.
1973 Derived
sign(UNumberSignDisplay style
) &&;
1976 * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common
1985 * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example:
1988 * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS)
1992 * The default is AUTO decimal separator display.
1995 * The decimal separator display strategy to use when rendering numbers.
1996 * @return The fluent chain
1997 * @see UNumberDecimalSeparatorDisplay
2000 Derived
decimal(UNumberDecimalSeparatorDisplay style
) const &;
2003 * Overload of decimal() for use on an rvalue reference.
2006 * The decimal separator display strategy to use when rendering numbers.
2007 * @return The fluent chain.
2011 Derived
decimal(UNumberDecimalSeparatorDisplay style
) &&;
2014 * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting.
2015 * Most common values:
2018 * <li>Multiply by 100: useful for percentages.
2019 * <li>Multiply by an arbitrary value: useful for unit conversions.
2023 * Pass an element from a {@link Scale} factory method to this setter. For example:
2026 * NumberFormatter::with().scale(Scale::powerOfTen(2))
2030 * The default is to not apply any multiplier.
2033 * The scale to apply when rendering numbers.
2034 * @return The fluent chain
2037 Derived
scale(const Scale
&scale
) const &;
2040 * Overload of scale() for use on an rvalue reference.
2043 * The scale to apply when rendering numbers.
2044 * @return The fluent chain.
2048 Derived
scale(const Scale
&scale
) &&;
2050 #ifndef U_HIDE_INTERNAL_API
2053 * Set the padding strategy. May be added in the future; see #13338.
2055 * @internal ICU 60: This API is ICU internal only.
2057 Derived
padding(const impl::Padder
&padder
) const &;
2060 Derived
padding(const impl::Padder
&padder
) &&;
2063 * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to
2064 * be built right away. A threshold of 0 prevents the data structures from being built.
2066 * @internal ICU 60: This API is ICU internal only.
2068 Derived
threshold(int32_t threshold
) const &;
2071 Derived
threshold(int32_t threshold
) &&;
2074 * Internal fluent setter to overwrite the entire macros object.
2076 * @internal ICU 60: This API is ICU internal only.
2078 Derived
macros(const impl::MacroProps
& macros
) const &;
2081 Derived
macros(const impl::MacroProps
& macros
) &&;
2084 Derived
macros(impl::MacroProps
&& macros
) const &;
2087 Derived
macros(impl::MacroProps
&& macros
) &&;
2089 #endif /* U_HIDE_INTERNAL_API */
2092 * Creates a skeleton string representation of this number formatter. A skeleton string is a
2093 * locale-agnostic serialized form of a number formatter.
2095 * Not all options are capable of being represented in the skeleton string; for example, a
2096 * DecimalFormatSymbols object. If any such option is encountered, the error code is set to
2097 * U_UNSUPPORTED_ERROR.
2099 * The returned skeleton is in normalized form, such that two number formatters with equivalent
2100 * behavior should produce the same skeleton.
2102 * @return A number skeleton string with behavior corresponding to this number formatter.
2105 UnicodeString
toSkeleton(UErrorCode
& status
) const;
2108 * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer
2109 * wrapping a heap-allocated copy of the current object.
2111 * This is equivalent to new-ing the move constructor with a value object
2114 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
2115 * nullptr on failure.
2118 LocalPointer
<Derived
> clone() const &;
2121 * Overload of clone for use on an rvalue reference.
2123 * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
2124 * nullptr on failure.
2127 LocalPointer
<Derived
> clone() &&;
2130 * Sets the UErrorCode if an error occurred in the fluent chain.
2131 * Preserves older error codes in the outErrorCode.
2132 * @return TRUE if U_FAILURE(outErrorCode)
2135 UBool
copyErrorTo(UErrorCode
&outErrorCode
) const {
2136 if (U_FAILURE(outErrorCode
)) {
2137 // Do not overwrite the older error code
2140 fMacros
.copyErrorTo(outErrorCode
);
2141 return U_FAILURE(outErrorCode
);
2144 // NOTE: Uses default copy and move constructors.
2147 impl::MacroProps fMacros
;
2149 // Don't construct me directly! Use (Un)LocalizedNumberFormatter.
2150 NumberFormatterSettings() = default;
2152 friend class LocalizedNumberFormatter
;
2153 friend class UnlocalizedNumberFormatter
;
2155 // Give NumberRangeFormatter access to the MacroProps
2156 friend void impl::touchRangeLocales(impl::RangeMacroProps
& macros
);
2157 friend class impl::NumberRangeFormatterImpl
;
2161 * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified.
2163 * Instances of this class are immutable and thread-safe.
2165 * @see NumberFormatter
2168 class U_I18N_API UnlocalizedNumberFormatter
2169 : public NumberFormatterSettings
<UnlocalizedNumberFormatter
>, public UMemory
{
2173 * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols,
2174 * formats, and other data for number display.
2177 * The locale to use when loading data for number formatting.
2178 * @return The fluent chain.
2181 LocalizedNumberFormatter
locale(const icu::Locale
&locale
) const &;
2184 * Overload of locale() for use on an rvalue reference.
2187 * The locale to use when loading data for number formatting.
2188 * @return The fluent chain.
2192 LocalizedNumberFormatter
locale(const icu::Locale
&locale
) &&;
2195 * Default constructor: puts the formatter into a valid but undefined state.
2199 UnlocalizedNumberFormatter() = default;
2202 * Returns a copy of this UnlocalizedNumberFormatter.
2205 UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter
&other
);
2209 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
2212 UnlocalizedNumberFormatter(UnlocalizedNumberFormatter
&& src
) U_NOEXCEPT
;
2215 * Copy assignment operator.
2218 UnlocalizedNumberFormatter
& operator=(const UnlocalizedNumberFormatter
& other
);
2221 * Move assignment operator:
2222 * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
2225 UnlocalizedNumberFormatter
& operator=(UnlocalizedNumberFormatter
&& src
) U_NOEXCEPT
;
2228 explicit UnlocalizedNumberFormatter(const NumberFormatterSettings
<UnlocalizedNumberFormatter
>& other
);
2230 explicit UnlocalizedNumberFormatter(
2231 NumberFormatterSettings
<UnlocalizedNumberFormatter
>&& src
) U_NOEXCEPT
;
2233 // To give the fluent setters access to this class's constructor:
2234 friend class NumberFormatterSettings
<UnlocalizedNumberFormatter
>;
2236 // To give NumberFormatter::with() access to this class's constructor:
2237 friend class NumberFormatter
;
2241 * A NumberFormatter that has a locale associated with it; this means .format() methods are available.
2243 * Instances of this class are immutable and thread-safe.
2245 * @see NumberFormatter
2248 class U_I18N_API LocalizedNumberFormatter
2249 : public NumberFormatterSettings
<LocalizedNumberFormatter
>, public UMemory
{
2252 * Format the given integer number to a string using the settings specified in the NumberFormatter fluent
2256 * The number to format.
2258 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2259 * @return A FormattedNumber object; call .toString() to get the string.
2262 FormattedNumber
formatInt(int64_t value
, UErrorCode
&status
) const;
2265 * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting
2269 * The number to format.
2271 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2272 * @return A FormattedNumber object; call .toString() to get the string.
2275 FormattedNumber
formatDouble(double value
, UErrorCode
&status
) const;
2278 * Format the given decimal number to a string using the settings
2279 * specified in the NumberFormatter fluent setting chain.
2280 * The syntax of the unformatted number is a "numeric string"
2281 * as defined in the Decimal Arithmetic Specification, available at
2282 * http://speleotrove.com/decimal
2285 * The number to format.
2287 * Set to an ErrorCode if one occurred in the setter chain or during formatting.
2288 * @return A FormattedNumber object; call .toString() to get the string.
2291 FormattedNumber
formatDecimal(StringPiece value
, UErrorCode
& status
) const;
2293 #ifndef U_HIDE_INTERNAL_API
2296 * Set whether DecimalFormatSymbols copy is deep (clone)
2297 * or shallow (pointer copy). Apple <rdar://problem/49955427>
2300 void setDFSShallowCopy(UBool shallow
);
2302 /** Internal method.
2305 FormattedNumber
formatDecimalQuantity(const impl::DecimalQuantity
& dq
, UErrorCode
& status
) const;
2307 /** Internal method for DecimalFormat compatibility.
2310 void getAffixImpl(bool isPrefix
, bool isNegative
, UnicodeString
& result
, UErrorCode
& status
) const;
2313 * Internal method for testing.
2316 const impl::NumberFormatterImpl
* getCompiled() const;
2319 * Internal method for testing.
2322 int32_t getCallCount() const;
2324 #endif /* U_HIDE_INTERNAL_API */
2327 * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use
2328 * of this number formatter with APIs that need an object of that type, such as MessageFormat.
2330 * This API is not intended to be used other than for enabling API compatibility. The formatDouble,
2331 * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format
2332 * object returned by this method.
2334 * The caller owns the returned object and must delete it when finished.
2336 * @return A Format wrapping this LocalizedNumberFormatter.
2339 Format
* toFormat(UErrorCode
& status
) const;
2342 * Default constructor: puts the formatter into a valid but undefined state.
2346 LocalizedNumberFormatter() = default;
2349 * Returns a copy of this LocalizedNumberFormatter.
2352 LocalizedNumberFormatter(const LocalizedNumberFormatter
&other
);
2356 * The source LocalizedNumberFormatter will be left in a valid but undefined state.
2359 LocalizedNumberFormatter(LocalizedNumberFormatter
&& src
) U_NOEXCEPT
;
2362 * Copy assignment operator.
2365 LocalizedNumberFormatter
& operator=(const LocalizedNumberFormatter
& other
);
2368 * Move assignment operator:
2369 * The source LocalizedNumberFormatter will be left in a valid but undefined state.
2372 LocalizedNumberFormatter
& operator=(LocalizedNumberFormatter
&& src
) U_NOEXCEPT
;
2374 #ifndef U_HIDE_INTERNAL_API
2377 * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path
2378 * for the first few calls, and compiling a more efficient data structure if called repeatedly.
2381 * This function is very hot, being called in every call to the number formatting pipeline.
2384 * The results object. This method will mutate it to save the results.
2388 void formatImpl(impl::UFormattedNumberData
*results
, UErrorCode
&status
) const;
2390 #endif /* U_HIDE_INTERNAL_API */
2393 * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own.
2396 ~LocalizedNumberFormatter();
2399 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal
2400 // header, and LocalPointer needs the full class definition in order to delete the instance.
2401 const impl::NumberFormatterImpl
* fCompiled
{nullptr};
2402 char fUnsafeCallCount
[8] {}; // internally cast to u_atomic_int32_t
2404 explicit LocalizedNumberFormatter(const NumberFormatterSettings
<LocalizedNumberFormatter
>& other
);
2406 explicit LocalizedNumberFormatter(NumberFormatterSettings
<LocalizedNumberFormatter
>&& src
) U_NOEXCEPT
;
2408 LocalizedNumberFormatter(const impl::MacroProps
¯os
, const Locale
&locale
);
2410 LocalizedNumberFormatter(impl::MacroProps
&¯os
, const Locale
&locale
);
2414 void lnfMoveHelper(LocalizedNumberFormatter
&& src
);
2417 * @return true if the compiled formatter is available.
2419 bool computeCompiled(UErrorCode
& status
) const;
2421 // To give the fluent setters access to this class's constructor:
2422 friend class NumberFormatterSettings
<UnlocalizedNumberFormatter
>;
2423 friend class NumberFormatterSettings
<LocalizedNumberFormatter
>;
2425 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor:
2426 friend class UnlocalizedNumberFormatter
;
2430 * The result of a number formatting operation. This class allows the result to be exported in several data types,
2431 * including a UnicodeString and a FieldPositionIterator.
2433 * Instances of this class are immutable and thread-safe.
2437 class U_I18N_API FormattedNumber
: public UMemory
, public FormattedValue
{
2441 * Default constructor; makes an empty FormattedNumber.
2445 : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR
) {}
2448 * Move constructor: Leaves the source FormattedNumber in an undefined state.
2451 FormattedNumber(FormattedNumber
&& src
) U_NOEXCEPT
;
2454 * Destruct an instance of FormattedNumber.
2457 virtual ~FormattedNumber() U_OVERRIDE
;
2459 /** Copying not supported; use move constructor instead. */
2460 FormattedNumber(const FormattedNumber
&) = delete;
2462 /** Copying not supported; use move assignment instead. */
2463 FormattedNumber
& operator=(const FormattedNumber
&) = delete;
2466 * Move assignment: Leaves the source FormattedNumber in an undefined state.
2469 FormattedNumber
& operator=(FormattedNumber
&& src
) U_NOEXCEPT
;
2471 // Copybrief: this method is older than the parent method
2473 * @copybrief FormattedValue::toString()
2475 * For more information, see FormattedValue::toString()
2479 UnicodeString
toString(UErrorCode
& status
) const U_OVERRIDE
;
2481 // Copydoc: this method is new in ICU 64
2482 /** @copydoc FormattedValue::toTempString() */
2483 UnicodeString
toTempString(UErrorCode
& status
) const U_OVERRIDE
;
2485 // Copybrief: this method is older than the parent method
2487 * @copybrief FormattedValue::appendTo()
2489 * For more information, see FormattedValue::appendTo()
2493 Appendable
&appendTo(Appendable
& appendable
, UErrorCode
& status
) const U_OVERRIDE
;
2495 // Copydoc: this method is new in ICU 64
2496 /** @copydoc FormattedValue::nextPosition() */
2497 UBool
nextPosition(ConstrainedFieldPosition
& cfpos
, UErrorCode
& status
) const U_OVERRIDE
;
2500 * Determines the start (inclusive) and end (exclusive) indices of the next occurrence of the given
2501 * <em>field</em> in the output string. This allows you to determine the locations of, for example,
2502 * the integer part, fraction part, or symbols.
2504 * This is a simpler but less powerful alternative to {@link #nextPosition}.
2506 * If a field occurs just once, calling this method will find that occurrence and return it. If a
2507 * field occurs multiple times, this method may be called repeatedly with the following pattern:
2510 * FieldPosition fpos(UNUM_GROUPING_SEPARATOR_FIELD);
2511 * while (formattedNumber.nextFieldPosition(fpos, status)) {
2512 * // do something with fpos.
2516 * This method is useful if you know which field to query. If you want all available field position
2517 * information, use {@link #nextPosition} or {@link #getAllFieldPositions}.
2519 * @param fieldPosition
2520 * Input+output variable. On input, the "field" property determines which field to look
2521 * up, and the "beginIndex" and "endIndex" properties determine where to begin the search.
2522 * On output, the "beginIndex" is set to the beginning of the first occurrence of the
2523 * field with either begin or end indices after the input indices; "endIndex" is set to
2524 * the end of that occurrence of the field (exclusive index). If a field position is not
2525 * found, the method returns FALSE and the FieldPosition may or may not be changed.
2527 * Set if an error occurs while populating the FieldPosition.
2528 * @return TRUE if a new occurrence of the field was found; FALSE otherwise.
2530 * @see UNumberFormatFields
2532 UBool
nextFieldPosition(FieldPosition
& fieldPosition
, UErrorCode
& status
) const;
2535 * Export the formatted number to a FieldPositionIterator. This allows you to determine which characters in
2536 * the output string correspond to which <em>fields</em>, such as the integer part, fraction part, and sign.
2538 * This is an alternative to the more powerful #nextPosition() API.
2540 * If information on only one field is needed, use #nextPosition() or #nextFieldPosition() instead.
2543 * The FieldPositionIterator to populate with all of the fields present in the formatted number.
2545 * Set if an error occurs while populating the FieldPositionIterator.
2547 * @see UNumberFormatFields
2549 void getAllFieldPositions(FieldPositionIterator
&iterator
, UErrorCode
&status
) const;
2551 #ifndef U_HIDE_INTERNAL_API
2554 * Gets the raw DecimalQuantity for plural rule selection.
2557 void getDecimalQuantity(impl::DecimalQuantity
& output
, UErrorCode
& status
) const;
2560 * Populates the mutable builder type FieldPositionIteratorHandler.
2563 void getAllFieldPositionsImpl(FieldPositionIteratorHandler
& fpih
, UErrorCode
& status
) const;
2565 #endif /* U_HIDE_INTERNAL_API */
2568 // Can't use LocalPointer because UFormattedNumberData is forward-declared
2569 const impl::UFormattedNumberData
*fData
;
2571 // Error code for the terminal methods
2572 UErrorCode fErrorCode
;
2575 * Internal constructor from data type. Adopts the data pointer.
2578 explicit FormattedNumber(impl::UFormattedNumberData
*results
)
2579 : fData(results
), fErrorCode(U_ZERO_ERROR
) {}
2581 explicit FormattedNumber(UErrorCode errorCode
)
2582 : fData(nullptr), fErrorCode(errorCode
) {}
2584 // To give LocalizedNumberFormatter format methods access to this class's constructor:
2585 friend class LocalizedNumberFormatter
;
2587 // To give C API access to internals
2588 friend struct impl::UFormattedNumberImpl
;
2592 * See the main description in numberformatter.h for documentation and examples.
2596 class U_I18N_API NumberFormatter final
{
2599 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at
2602 * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining.
2605 static UnlocalizedNumberFormatter
with();
2608 * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call
2612 * The locale from which to load formats and symbols for number formatting.
2613 * @return A {@link LocalizedNumberFormatter}, to be used for chaining.
2616 static LocalizedNumberFormatter
withLocale(const Locale
&locale
);
2619 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
2620 * on a given number skeleton string.
2622 * It is possible for an error to occur while parsing. See the overload of this method if you are
2623 * interested in the location of a possible parse error.
2626 * The skeleton string off of which to base this NumberFormatter.
2628 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
2629 * @return An UnlocalizedNumberFormatter, to be used for chaining.
2632 static UnlocalizedNumberFormatter
forSkeleton(const UnicodeString
& skeleton
, UErrorCode
& status
);
2635 * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
2636 * on a given number skeleton string.
2638 * If an error occurs while parsing the skeleton string, the offset into the skeleton string at
2639 * which the error occurred will be saved into the UParseError, if provided.
2642 * The skeleton string off of which to base this NumberFormatter.
2644 * A parse error struct populated if an error occurs when parsing.
2645 * If no error occurs, perror.offset will be set to -1.
2647 * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
2648 * @return An UnlocalizedNumberFormatter, to be used for chaining.
2651 static UnlocalizedNumberFormatter
forSkeleton(const UnicodeString
& skeleton
,
2652 UParseError
& perror
, UErrorCode
& status
);
2655 * Use factory methods instead of the constructor to create a NumberFormatter.
2657 NumberFormatter() = delete;
2660 } // namespace number
2663 #endif // U_HIDE_DRAFT_API
2665 #endif // __NUMBERFORMATTER_H__
2667 #endif /* #if !UCONFIG_NO_FORMATTING */