/** *\file *\briefC++API:All-in-oneformatterforlocalizednumbers,currencies,andunits. * *Forafulllistofoptions,seeicu::number::NumberFormatterSettings. * *<pre> *// Most basic usage: *NumberFormatter::withLocale(...).format(123).toString();// 1,234 in en-US * *// Custom notation, unit, and rounding precision: *NumberFormatter::with() *.notation(Notation::compactShort()) *.unit(CurrencyUnit("EUR",status)) *.precision(Precision::maxDigits(2)) *.locale(...) *.format(1234) *.toString();// €1.2K in en-US * *// Create a formatter in a singleton by value for use later: *staticconstLocalizedNumberFormatterformatter=NumberFormatter::withLocale(...) *.unit(NoUnit::percent()) *.precision(Precision::fixedFraction(3)); *formatter.format(5.9831).toString();// 5.983% in en-US * *// Create a "template" in a singleton unique_ptr but without setting a locale until the call site: *std::unique_ptr<UnlocalizedNumberFormatter>template=NumberFormatter::with() *.sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS) *.unit(MeasureUnit::getMeter()) *.unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME) *.clone(); *template->locale(...).format(1234).toString();// +1,234 meters in en-US *</pre> * *<p> *ThisAPIoffersmorefeaturesthanDecimalFormatandisgearedtowardnewusersofICU. * *<p> *NumberFormatterinstances(i.e.,LocalizedNumberFormatterandUnlocalizedNumberFormatter) *areimmutableandthreadsafe.Thismeansthatinvokingaconfigurationmethodhasno *effectonthereceivinginstance;youmuststoreandusethenewnumberformatterinstanceitreturnsinstead. * *<pre> *UnlocalizedNumberFormatterformatter=UnlocalizedNumberFormatter::with().notation(Notation::scientific()); *formatter.precision(Precision.maxFraction(2));// does nothing! *formatter.locale(Locale.getEnglish()).format(9.8765).toString();// prints "9.8765E0", not "9.88E0" *</pre> * *<p> *ThisAPIisbasedonthe<em>fluent</em>designpatternpopularizedbylibrariessuchasGoogle'sGuava.For *extensivedetailsonthedesignofthisAPI,read<ahref="https://goo.gl/szi5VB">the design doc</a>. * *<p> *Note:Toformatmonetary/currencyvalues,specifythecurrencyinthe`.unit()`function. * *@authorShaneCarr
*/
U_NAMESPACE_BEGIN
// Forward declarations: class IFixedDecimal; class FieldPositionIteratorHandler; class FormattedStringBuilder;
namespace numparse::impl {
// Forward declarations: class NumberParserImpl; class MultiplierParseHandler;
} // namespace numparse::impl
namespace units {
// Forward declarations: class UnitsRouter;
} // namespace units
namespace number { // icu::number
// Forward declarations: class UnlocalizedNumberFormatter; class LocalizedNumberFormatter; class SimpleNumberFormatter; class FormattedNumber; class Notation; class ScientificNotation; class Precision; class FractionPrecision; class CurrencyPrecision; class IncrementPrecision; class IntegerWidth;
namespace impl {
// can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes /** *Datatypeforminimum/maximumfractiondigits.MustbeabletoholdkMaxIntFracSig. * *@internal
*/ typedef int16_t digits_t;
// Forward declarations: class Padder; struct MacroProps; struct MicroProps; class DecimalQuantity; class UFormattedNumberData; class NumberFormatterImpl; struct ParsedPatternInfo; class ScientificModifier; class MultiplierProducer; class RoundingImpl; class ScientificHandler; class Modifier; class AffixPatternProvider; class NumberPropertyMapper; struct DecimalFormatProperties; class MultiplierFormatHandler; class CurrencySymbols; class GeneratorHelpers; class DecNum; class NumberRangeFormatterImpl; struct RangeMacroProps; struct UFormattedNumberImpl; class MutablePatternModifier; class ImmutablePatternModifier; struct DecimalFormatWarehouse; struct SimpleMicroProps; class AdoptingSignumModifierStore;
// Used for strange increments like 3.14.
RND_INCREMENT,
// Used for increments with 1 as the only digit. This is different than fraction // rounding because it supports having additional trailing zeros. For example, this // class is used to round with the increment 0.010.
RND_INCREMENT_ONE,
// Used for increments with 5 as the only digit (nickel rounding).
RND_INCREMENT_FIVE,
RND_CURRENCY,
RND_ERROR
} fType;
union PrecisionUnion { /** @internal (private) */ struct FractionSignificantSettings { // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT /** @internal (private) */
impl::digits_t fMinFrac; /** @internal (private) */
impl::digits_t fMaxFrac; /** @internal (private) */
impl::digits_t fMinSig; /** @internal (private) */
impl::digits_t fMaxSig; /** @internal (private) */
UNumberRoundingPriority fPriority; /** *Whethertoretaintrailingzerosbasedonthelooserstrategy. *@internal(private)
*/ bool fRetain;
} fracSig; /** @internal (private) */ struct IncrementSettings { // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE // Note: This is a union, so we shouldn't own memory, since // the default destructor would leak it. /** @internal (private) */
uint64_t fIncrement; /** @internal (private) */
impl::digits_t fIncrementMagnitude; /** @internal (private) */
impl::digits_t fMinFrac;
} increment;
UCurrencyUsage currencyUsage; // For RND_CURRENCY
UErrorCode errorCode; // For RND_ERROR
} fUnion;
UBool copyErrorTo(UErrorCode &status) const { if (fType == RND_ERROR) {
status = fUnion.errorCode; return true;
} returnfalse;
}
// On the parent type so that this method can be called internally on Precision instances.
Precision withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const;
// To allow MacroProps/MicroProps to initialize empty instances: friendstruct impl::MacroProps; friendstruct impl::MicroProps;
// To allow NumberFormatterImpl to access isBogus() and perform other operations: friendclass impl::NumberFormatterImpl;
// To allow the helper class MultiplierFormatHandler access to private fields: friendclass impl::MultiplierFormatHandler;
// To allow access to the skeleton generation code: friendclass impl::GeneratorHelpers;
// To allow access to parsing code: friendclass ::icu::numparse::impl::NumberParserImpl; friendclass ::icu::numparse::impl::MultiplierParseHandler;
};
namespace impl {
// Do not enclose entire StringProp with #ifndef U_HIDE_INTERNAL_API, needed for a protected field. // And do not enclose its class boilerplate within #ifndef U_HIDE_INTERNAL_API. /** *ManagesNumberFormatterSettings::usage()'schar*instanceontheheap. *@internal
*/ class U_I18N_API StringProp : public UMemory {
// Allow MacroProps/MicroProps to initialize empty instances and to call // copyErrorTo(). friendstruct impl::MacroProps;
};
// Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field /** @internal */ class U_I18N_API SymbolsWrapper : public UMemory {
public: /** @internal */
SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {}
union { const DecimalFormatSymbols *dfs; const NumberingSystem *ns;
} fPtr;
void doCopyFrom(const SymbolsWrapper &other);
void doMoveFrom(SymbolsWrapper&& src);
void doCleanup();
};
// Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field /** @internal */ class U_I18N_API Grouper : public UMemory {
public: #ifndef U_HIDE_INTERNAL_API /** @internal */ static Grouper forStrategy(UNumberGroupingStrategy grouping);
// To allow MacroProps/MicroProps to initialize empty instances: friendstruct MacroProps; friendstruct MicroProps; friendstruct SimpleMicroProps;
// To allow NumberFormatterImpl to access isBogus() and perform other operations: friendclass NumberFormatterImpl; friendclass ::icu::number::SimpleNumberFormatter;
// To allow NumberParserImpl to perform setLocaleData(): friendclass ::icu::numparse::impl::NumberParserImpl;
// To allow access to the skeleton generation code: friendclass impl::GeneratorHelpers;
};
// Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field /** @internal */ class U_I18N_API Padder : public UMemory {
public: #ifndef U_HIDE_INTERNAL_API /** @internal */ static Padder none();
// To allow MacroProps/MicroProps to initialize empty instances: friendstruct MacroProps; friendstruct MicroProps;
// To allow NumberFormatterImpl to access isBogus() and perform other operations: friendclass impl::NumberFormatterImpl;
// To allow access to the skeleton generation code: friendclass impl::GeneratorHelpers;
};
// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field. // U_I18N_API because intltest uses it. /** @internal */ struct U_I18N_API_CLASS MacroProps : public UMemory { /** @internal */
Notation notation;
/** @internal */
MeasureUnit unit; // = MeasureUnit(); (the base dimensionless unit)
/** @internal */
MeasureUnit perUnit; // = MeasureUnit(); (the base dimensionless unit)
#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER) // Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method // is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation // inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is // fully defined. However, since each translation unit explicitly instantiates all the necessary template classes, // they will all be passed to the linker, and the linker will still find and export all the class members. #pragma warning(push) #pragma warning(disable: 4661) #endif
/**
* Specifies the minimum and maximum number of digits to render before the decimal mark.
*
* <ul>
* <li>Zero minimum integer digits: ".08"
* <li>One minimum integer digit: "0.08"
* <li>Two minimum integer digits: "00.08"
* </ul>
*
* <p>
* Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example:
*
* <pre>
* NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2))
* </pre>
*
* The default is to have one minimum integer digit.
*
* @param style
* The integer width to use.
* @return The fluent chain.
* @see IntegerWidth
* @stable ICU 60
*/
Derived integerWidth(const IntegerWidth &style) const &;
/**
* Overload of integerWidth() for use on an rvalue reference.
*
* @param style
* The integer width to use.
* @return The fluent chain.
* @see #integerWidth
* @stable ICU 62
*/
Derived integerWidth(const IntegerWidth &style) &&;
/**
* Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering
* numbers.
*
* <ul>
* <li><em>en_US</em> symbols: "12,345.67"
* <li><em>fr_FR</em> symbols: "12345,67"
* <li><em>de_CH</em> symbols: "12’345.67"
* <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇"
* </ul>
*
* <p>
* Pass this method an instance of {@link DecimalFormatSymbols}. For example:
*
* <pre>
* NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status))
* </pre>
*
* <p>
* <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale.
* In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar
* numbering system.
*
* <p>
* <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object
* after passing it into the fluent chain will not be seen.
*
* <p>
* <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
* or NumberingSystem.
*
* <p>
* The default is to choose the symbols based on the locale specified in the fluent chain.
*
* @param symbols
* The DecimalFormatSymbols to use.
* @return The fluent chain.
* @see DecimalFormatSymbols
* @stable ICU 60
*/
Derived symbols(const DecimalFormatSymbols &symbols) const &;
/**
* Overload of symbols() for use on an rvalue reference.
*
* @param symbols
* The DecimalFormatSymbols to use.
* @return The fluent chain.
* @see #symbols
* @stable ICU 62
*/
Derived symbols(const DecimalFormatSymbols &symbols) &&;
/**
* Specifies that the given numbering system should be used when fetching symbols.
*
* <ul>
* <li>Latin numbering system: "12,345"
* <li>Myanmar numbering system: "၁၂,၃၄၅"
* <li>Math Sans Bold numbering system: ","
* </ul>
*
* <p>
* Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin
* alphabet numbering system (ASCII digits):
*
* <pre>
* NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status))
* </pre>
*
* <p>
* <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
* or NumberingSystem.
*
* <p>
* The default is to choose the best numbering system for the locale.
*
* <p>
* This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods.
*
* @param symbols
* The NumberingSystem to use.
* @return The fluent chain.
* @see NumberingSystem
* @stable ICU 60
*/
Derived adoptSymbols(NumberingSystem *symbols) const &;
/**
* Overload of adoptSymbols() for use on an rvalue reference.
*
* @param symbols
* The NumberingSystem to use.
* @return The fluent chain.
* @see #adoptSymbols
* @stable ICU 62
*/
Derived adoptSymbols(NumberingSystem *symbols) &&;
/**
* Sets the width of the unit (measure unit or currency). Most common values:
*
* <ul>
* <li>Short: "$12.00", "12 m"
* <li>ISO Code: "USD 12.00"
* <li>Full name: "12.00 US dollars", "12 meters"
* </ul>
*
* <p>
* Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example:
*
* <pre>
* NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
* </pre>
*
* <p>
* The default is the SHORT width.
*
* @param width
* The width to use when rendering numbers.
* @return The fluent chain
* @see UNumberUnitWidth
* @stable ICU 60
*/
Derived unitWidth(UNumberUnitWidth width) const &;
/**
* Overload of unitWidth() for use on an rvalue reference.
*
* @param width
* The width to use when rendering numbers.
* @return The fluent chain.
* @see #unitWidth
* @stable ICU 62
*/
Derived unitWidth(UNumberUnitWidth width) &&;
/**
* Sets the plus/minus sign display strategy. Most common values:
*
* <ul>
* <li>Auto: "123", "-123"
* <li>Always: "+123", "-123"
* <li>Accounting: "$123", "($123)"
* </ul>
*
* <p>
* Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example:
*
* <pre>
* NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
* </pre>
*
* <p>
* The default is AUTO sign display.
*
* @param style
* The sign display strategy to use when rendering numbers.
* @return The fluent chain
* @see UNumberSignDisplay
* @stable ICU 60
*/
Derived sign(UNumberSignDisplay style) const &;
/**
* Overload of sign() for use on an rvalue reference.
*
* @param style
* The sign display strategy to use when rendering numbers.
* @return The fluent chain.
* @see #sign
* @stable ICU 62
*/
Derived sign(UNumberSignDisplay style) &&;
/**
* Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common
* values:
*
* <ul>
* <li>Auto: "1"
* <li>Always: "1."
* </ul>
*
* <p>
* Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example:
*
* <pre>
* NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS)
* </pre>
*
* <p>
* The default is AUTO decimal separator display.
*
* @param style
* The decimal separator display strategy to use when rendering numbers.
* @return The fluent chain
* @see UNumberDecimalSeparatorDisplay
* @stable ICU 60
*/
Derived decimal(UNumberDecimalSeparatorDisplay style) const &;
/**
* Overload of decimal() for use on an rvalue reference.
*
* @param style
* The decimal separator display strategy to use when rendering numbers.
* @return The fluent chain.
* @see #decimal
* @stable ICU 62
*/
Derived decimal(UNumberDecimalSeparatorDisplay style) &&;
/**
* Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting.
* Most common values:
*
* <ul>
* <li>Multiply by 100: useful for percentages.
* <li>Multiply by an arbitrary value: useful for unit conversions.
* </ul>
*
* <p>
* Pass an element from a {@link Scale} factory method to this setter. For example:
*
* <pre>
* NumberFormatter::with().scale(Scale::powerOfTen(2))
* </pre>
*
* <p>
* The default is to not apply any multiplier.
*
* @param scale
* The scale to apply when rendering numbers.
* @return The fluent chain
* @stable ICU 62
*/
Derived scale(const Scale &scale) const &;
/**
* Overload of scale() for use on an rvalue reference.
*
* @param scale
* The scale to apply when rendering numbers.
* @return The fluent chain.
* @see #scale
* @stable ICU 62
*/
Derived scale(const Scale &scale) &&;
/**
* Specifies the usage for which numbers will be formatted ("person-height",
* "road", "rainfall", etc.)
*
* When a `usage` is specified, the output unit will change depending on the
* `Locale` and the unit quantity. For example, formatting length
* measurements specified in meters:
*
* `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")`
* * When formatting 0.25, the output will be "10 inches".
* * When formatting 1.50, the output will be "4 feet and 11 inches".
*
* The input unit specified via unit() determines the type of measurement
* being formatted (e.g. "length" when the unit is "foot"). The usage
* requested will be looked for only within this category of measurement
* units.
*
* The output unit can be found via FormattedNumber::getOutputUnit().
*
* If the usage has multiple parts (e.g. "land-agriculture-grain") and does
* not match a known usage preference, the last part will be dropped
* repeatedly until a match is found (e.g. trying "land-agriculture", then
* "land"). If a match is still not found, usage will fall back to
* "default".
*
* Setting usage to an empty string clears the usage (disables usage-based
* localized formatting).
*
* Setting a usage string but not a correct input unit will result in an
* U_ILLEGAL_ARGUMENT_ERROR.
*
* When using usage, specifying rounding or precision is unnecessary.
* Specifying a precision in some manner will override the default
* formatting.
*
* @param usage A `usage` parameter from the units resource. See the
* unitPreferenceData in *source/data/misc/units.txt*, generated from
* `unitPreferenceData` in [CLDR's
* supplemental/units.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/units.xml).
* @return The fluent chain.
* @stable ICU 68
*/
Derived usage(StringPiece usage) const &;
/**
* Overload of usage() for use on an rvalue reference.
*
* @param usage The unit `usage`.
* @return The fluent chain.
* @stable ICU 68
*/
Derived usage(StringPiece usage) &&;
/**
* Specifies the DisplayOptions. For example, UDisplayOptionsGrammaticalCase specifies
* the desired case for a unit formatter's output (e.g. accusative, dative, genitive).
*
* @param displayOptions
* @return The fluent chain.
* @stable ICU 72
*/
Derived displayOptions(const DisplayOptions &displayOptions) const &;
/**
* Overload of displayOptions() for use on an rvalue reference.
*
* @param displayOptions
* @return The fluent chain.
* @stable ICU 72
*/
Derived displayOptions(const DisplayOptions &displayOptions) &&;
#ifndef U_HIDE_INTERNAL_API
/**
* NOTE: Use `displayOptions` instead. This method was part of
* an internal technology preview in ICU 69, but will be removed
* in ICU 73, in favor of `displayOptions`
*
* Specifies the desired case for a unit formatter's output (e.g.
* accusative, dative, genitive).
*
* @internal
*/
Derived unitDisplayCase(StringPiece unitDisplayCase) const &;
/**
* NOTE: Use `displayOptions` instead. This method was part of
* an internal technology preview in ICU 69, but will be removed
* in ICU 73, in favor of `displayOptions`
*
* Overload of unitDisplayCase() for use on an rvalue reference.
*
* @internal
*/
Derived unitDisplayCase(StringPiece unitDisplayCase) &&;
#endif // U_HIDE_INTERNAL_API
#ifndef U_HIDE_INTERNAL_API
/**
* Set the padding strategy. May be added in the future; see #13338.
*
* @internal ICU 60: This API is ICU internal only.
*/
Derived padding(const impl::Padder &padder) const &;
/**
* Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to
* be built right away. A threshold of 0 prevents the data structures from being built.
*
* @internal ICU 60: This API is ICU internal only.
*/
Derived threshold(int32_t threshold) const &;
/**
* Creates a skeleton string representation of this number formatter. A skeleton string is a
* locale-agnostic serialized form of a number formatter.
*
* Not all options are capable of being represented in the skeleton string; for example, a
* DecimalFormatSymbols object. If any such option is encountered, the error code is set to
* U_UNSUPPORTED_ERROR.
*
* The returned skeleton is in normalized form, such that two number formatters with equivalent
* behavior should produce the same skeleton.
*
* For more information on number skeleton strings, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
*
* @return A number skeleton string with behavior corresponding to this number formatter.
* @stable ICU 62
*/
UnicodeString toSkeleton(UErrorCode& status) const;
/**
* Returns the current (Un)LocalizedNumberFormatter as a LocalPointer
* wrapping a heap-allocated copy of the current object.
*
* This is equivalent to new-ing the move constructor with a value object
* as the argument.
*
* @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
* nullptr on failure.
* @stable ICU 64
*/
LocalPointer<Derived> clone() const &;
/**
* Overload of clone for use on an rvalue reference.
*
* @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
* nullptr on failure.
* @stable ICU 64
*/
LocalPointer<Derived> clone() &&;
/**
* Sets the UErrorCode if an error occurred in the fluent chain.
* Preserves older error codes in the outErrorCode.
* @return true if U_FAILURE(outErrorCode)
* @stable ICU 60
*/
UBool copyErrorTo(UErrorCode &outErrorCode) const {
if (U_FAILURE(outErrorCode)) {
// Do not overwrite the older error code
return true;
}
fMacros.copyErrorTo(outErrorCode);
return U_FAILURE(outErrorCode);
}
// NOTE: Uses default copy and move constructors.
private:
impl::MacroProps fMacros;
// Don't construct me directly! Use (Un)LocalizedNumberFormatter.
NumberFormatterSettings() = default;
friend class LocalizedNumberFormatter;
friend class UnlocalizedNumberFormatter;
// Give NumberRangeFormatter access to the MacroProps
friend void impl::touchRangeLocales(impl::RangeMacroProps& macros);
friend class impl::NumberRangeFormatterImpl;
};
// Explicit instantiations in source/i18n/number_fluent.cpp.
// (MSVC treats imports/exports of explicit instantiations differently.)
#ifndef _MSC_VER
extern template class NumberFormatterSettings<UnlocalizedNumberFormatter>;
extern template class NumberFormatterSettings<LocalizedNumberFormatter>;
#endif
/**
* A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified.
*
* Instances of this class are immutable and thread-safe.
*
* @see NumberFormatter
* @stable ICU 60
*/
class U_I18N_API UnlocalizedNumberFormatter
: public NumberFormatterSettings<UnlocalizedNumberFormatter>, public UMemory {
public:
/**
* Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols,
* formats, and other data for number display.
*
* @param locale
* The locale to use when loading data for number formatting.
* @return The fluent chain.
* @stable ICU 60
*/
LocalizedNumberFormatter locale(const icu::Locale &locale) const &;
/**
* Overload of locale() for use on an rvalue reference.
*
* @param locale
* The locale to use when loading data for number formatting.
* @return The fluent chain.
* @see #locale
* @stable ICU 62
*/
LocalizedNumberFormatter locale(const icu::Locale &locale) &&;
/**
* Default constructor: puts the formatter into a valid but undefined state.
*
* @stable ICU 62
*/
UnlocalizedNumberFormatter() = default;
/**
* Returns a copy of this UnlocalizedNumberFormatter.
* @stable ICU 60
*/
UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other);
/**
* Move constructor:
* The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
* @stable ICU 62
*/
UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) noexcept;
/**
* Move assignment operator:
* The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
* @stable ICU 62
*/
UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) noexcept;
// To give the fluent setters access to this class's constructor:
friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
// To give NumberFormatter::with() access to this class's constructor:
friend class NumberFormatter;
// To give LNF::withoutLocale() access to this class's constructor:
friend class LocalizedNumberFormatter;
};
/**
* A NumberFormatter that has a locale associated with it; this means .format() methods are available.
*
* Instances of this class are immutable and thread-safe.
*
* @see NumberFormatter
* @stable ICU 60
*/
class U_I18N_API LocalizedNumberFormatter
: public NumberFormatterSettings<LocalizedNumberFormatter>, public UMemory {
public:
/**
* Format the given integer number to a string using the settings specified in the NumberFormatter fluent
* setting chain.
*
* @param value
* The number to format.
* @param status
* Set to an ErrorCode if one occurred in the setter chain or during formatting.
* @return A FormattedNumber object; call .toString() to get the string.
* @stable ICU 60
*/
FormattedNumber formatInt(int64_t value, UErrorCode &status) const;
/**
* Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting
* chain.
*
* @param value
* The number to format.
* @param status
* Set to an ErrorCode if one occurred in the setter chain or during formatting.
* @return A FormattedNumber object; call .toString() to get the string.
* @stable ICU 60
*/
FormattedNumber formatDouble(double value, UErrorCode &status) const;
/**
* Format the given decimal number to a string using the settings
* specified in the NumberFormatter fluent setting chain.
* The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @param value
* The number to format.
* @param status
* Set to an ErrorCode if one occurred in the setter chain or during formatting.
* @return A FormattedNumber object; call .toString() to get the string.
* @stable ICU 60
*/
FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const;
/**
* Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use
* of this number formatter with APIs that need an object of that type, such as MessageFormat.
*
* This API is not intended to be used other than for enabling API compatibility. The formatDouble,
* formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format
* object returned by this method.
*
* The caller owns the returned object and must delete it when finished.
*
* @return A Format wrapping this LocalizedNumberFormatter.
* @stable ICU 62
*/
Format* toFormat(UErrorCode& status) const;
/**
* Disassociate the locale from this formatter.
*
* @return The fluent chain.
* @stable ICU 75
*/
UnlocalizedNumberFormatter withoutLocale() const &;
/**
* Overload of withoutLocale() for use on an rvalue reference.
*
* @return The fluent chain.
* @see #withoutLocale
* @stable ICU 75
*/
UnlocalizedNumberFormatter withoutLocale() &&;
/**
* Default constructor: puts the formatter into a valid but undefined state.
*
* @stable ICU 62
*/
LocalizedNumberFormatter() = default;
/**
* Returns a copy of this LocalizedNumberFormatter.
* @stable ICU 60
*/
LocalizedNumberFormatter(const LocalizedNumberFormatter &other);
/**
* Move constructor:
* The source LocalizedNumberFormatter will be left in a valid but undefined state.
* @stable ICU 62
*/
LocalizedNumberFormatter(LocalizedNumberFormatter&& src) noexcept;
/**
* Move assignment operator:
* The source LocalizedNumberFormatter will be left in a valid but undefined state.
* @stable ICU 62
*/
LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) noexcept;
#ifndef U_HIDE_INTERNAL_API
/**
* This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path
* for the first few calls, and compiling a more efficient data structure if called repeatedly.
*
* <p>
* This function is very hot, being called in every call to the number formatting pipeline.
*
* @param results
* The results object. This method will mutate it to save the results.
* @param status
* @internal
*/
void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const;
#endif /* U_HIDE_INTERNAL_API */
/**
* Destruct this LocalizedNumberFormatter, cleaning up any memory it might own.
* @stable ICU 60
*/
~LocalizedNumberFormatter();
private:
// Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal
// header, and LocalPointer needs the full class definition in order to delete the instance.
const impl::NumberFormatterImpl* fCompiled {nullptr};
char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t
// Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter
// from a DecimalFormat.
const impl::DecimalFormatWarehouse* fWarehouse {nullptr};
/**
* @return true if the compiled formatter is available.
*/
bool computeCompiled(UErrorCode& status) const;
// To give the fluent setters access to this class's constructor:
friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
friend class NumberFormatterSettings<LocalizedNumberFormatter>;
// To give UnlocalizedNumberFormatter::locale() access to this class's constructor:
friend class UnlocalizedNumberFormatter;
};
/**
* See the main description in numberformatter.h for documentation and examples.
*
* @stable ICU 60
*/
class U_I18N_API NumberFormatter final {
public:
/**
* Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at
* the call site.
*
* @return An {@link UnlocalizedNumberFormatter}, to be used for chaining.
* @stable ICU 60
*/
static UnlocalizedNumberFormatter with();
/**
* Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call
* site.
*
* @param locale
* The locale from which to load formats and symbols for number formatting.
* @return A {@link LocalizedNumberFormatter}, to be used for chaining.
* @stable ICU 60
*/
static LocalizedNumberFormatter withLocale(const Locale &locale);
/**
* Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
* on a given number skeleton string.
*
* It is possible for an error to occur while parsing. See the overload of this method if you are
* interested in the location of a possible parse error.
*
* For more information on number skeleton strings, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
*
* @param skeleton
* The skeleton string off of which to base this NumberFormatter.
* @param status
* Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
* @return An UnlocalizedNumberFormatter, to be used for chaining.
* @stable ICU 62
*/
static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status);
/**
* Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
* on a given number skeleton string.
*
* If an error occurs while parsing the skeleton string, the offset into the skeleton string at
* which the error occurred will be saved into the UParseError, if provided.
*
* For more information on number skeleton strings, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
*
* @param skeleton
* The skeleton string off of which to base this NumberFormatter.
* @param perror
* A parse error struct populated if an error occurs when parsing.
* If no error occurs, perror.offset will be set to -1.
* @param status
* Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
* @return An UnlocalizedNumberFormatter, to be used for chaining.
* @stable ICU 64
*/
static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton,
UParseError& perror, UErrorCode& status);
/**
* Use factory methods instead of the constructor to create a NumberFormatter.
*/
NumberFormatter() = delete;
};
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.