* This does not provide compound formatting for multiple units, * other than the ability to combine a time string with a relative date, * as in "next Tuesday at 3:45 PM". It also does not provide support * for determining which unit to use, such as deciding between "in 7 days" * and "in 1 week". * * @stable ICU 57 */ /** * The formatting style * @stable ICU 54 */ typedef enum UDateRelativeDateTimeFormatterStyle { /** * Everything spelled out. * @stable ICU 54 */ UDAT_STYLE_LONG, /** * Abbreviations used when possible. * @stable ICU 54 */ UDAT_STYLE_SHORT, /** * Use the shortest possible form. * @stable ICU 54 */ UDAT_STYLE_NARROW, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal UDateRelativeDateTimeFormatterStyle value. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ UDAT_STYLE_COUNT #endif /* U_HIDE_DEPRECATED_API */ } UDateRelativeDateTimeFormatterStyle; /** * Represents the unit for formatting a relative date. e.g "in 5 days" * or "next year" * @stable ICU 57 */ typedef enum URelativeDateTimeUnit { /** * Specifies that relative unit is year, e.g. "last year", * "in 5 years". * @stable ICU 57 */ UDAT_REL_UNIT_YEAR, /** * Specifies that relative unit is quarter, e.g. "last quarter", * "in 5 quarters". * @stable ICU 57 */ UDAT_REL_UNIT_QUARTER, /** * Specifies that relative unit is month, e.g. "last month", * "in 5 months". * @stable ICU 57 */ UDAT_REL_UNIT_MONTH, /** * Specifies that relative unit is week, e.g. "last week", * "in 5 weeks". * @stable ICU 57 */ UDAT_REL_UNIT_WEEK, /** * Specifies that relative unit is day, e.g. "yesterday", * "in 5 days". * @stable ICU 57 */ UDAT_REL_UNIT_DAY, /** * Specifies that relative unit is hour, e.g. "1 hour ago", * "in 5 hours". * @stable ICU 57 */ UDAT_REL_UNIT_HOUR, /** * Specifies that relative unit is minute, e.g. "1 minute ago", * "in 5 minutes". * @stable ICU 57 */ UDAT_REL_UNIT_MINUTE, /** * Specifies that relative unit is second, e.g. "1 second ago", * "in 5 seconds". * @stable ICU 57 */ UDAT_REL_UNIT_SECOND, /** * Specifies that relative unit is Sunday, e.g. "last Sunday", * "this Sunday", "next Sunday", "in 5 Sundays". * @stable ICU 57 */ UDAT_REL_UNIT_SUNDAY, /** * Specifies that relative unit is Monday, e.g. "last Monday", * "this Monday", "next Monday", "in 5 Mondays". * @stable ICU 57 */ UDAT_REL_UNIT_MONDAY, /** * Specifies that relative unit is Tuesday, e.g. "last Tuesday", * "this Tuesday", "next Tuesday", "in 5 Tuesdays". * @stable ICU 57 */ UDAT_REL_UNIT_TUESDAY, /** * Specifies that relative unit is Wednesday, e.g. "last Wednesday", * "this Wednesday", "next Wednesday", "in 5 Wednesdays". * @stable ICU 57 */ UDAT_REL_UNIT_WEDNESDAY, /** * Specifies that relative unit is Thursday, e.g. "last Thursday", * "this Thursday", "next Thursday", "in 5 Thursdays". * @stable ICU 57 */ UDAT_REL_UNIT_THURSDAY, /** * Specifies that relative unit is Friday, e.g. "last Friday", * "this Friday", "next Friday", "in 5 Fridays". * @stable ICU 57 */ UDAT_REL_UNIT_FRIDAY, /** * Specifies that relative unit is Saturday, e.g. "last Saturday", * "this Saturday", "next Saturday", "in 5 Saturdays". * @stable ICU 57 */ UDAT_REL_UNIT_SATURDAY, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal URelativeDateTimeUnit value. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ UDAT_REL_UNIT_COUNT #endif /* U_HIDE_DEPRECATED_API */ } URelativeDateTimeUnit; #ifndef U_HIDE_DRAFT_API /** * FieldPosition and UFieldPosition selectors for format fields * defined by RelativeDateTimeFormatter. * @draft ICU 64 */ typedef enum URelativeDateTimeFormatterField { /** * Represents a literal text string, like "tomorrow" or "days ago". * @draft ICU 64 */ UDAT_REL_LITERAL_FIELD, /** * Represents a number quantity, like "3" in "3 days ago". * @draft ICU 64 */ UDAT_REL_NUMERIC_FIELD, } URelativeDateTimeFormatterField; #endif // U_HIDE_DRAFT_API /** * Opaque URelativeDateTimeFormatter object for use in C programs. * @stable ICU 57 */ struct URelativeDateTimeFormatter; typedef struct URelativeDateTimeFormatter URelativeDateTimeFormatter; /**< C typedef for struct URelativeDateTimeFormatter. @stable ICU 57 */ /** * Open a new URelativeDateTimeFormatter object for a given locale using the * specified width and capitalizationContext, along with a number formatter * (if desired) to override the default formatter that would be used for * display of numeric field offsets. The default formatter typically rounds * toward 0 and has a minimum of 0 fraction digits and a maximum of 3 * fraction digits (i.e. it will show as many decimal places as necessary * up to 3, without showing trailing 0s). * * @param locale * The locale * @param nfToAdopt * A number formatter to set for this URelativeDateTimeFormatter * object (instead of the default decimal formatter). Ownership of * this UNumberFormat object will pass to the URelativeDateTimeFormatter * object (the URelativeDateTimeFormatter adopts the UNumberFormat), * which becomes responsible for closing it. If the caller wishes to * retain ownership of the UNumberFormat object, the caller must clone * it (with unum_clone) and pass the clone to ureldatefmt_open. May be * NULL to use the default decimal formatter. * @param width * The width - wide, short, narrow, etc. * @param capitalizationContext * A value from UDisplayContext that pertains to capitalization, e.g. * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE. * @param status * A pointer to a UErrorCode to receive any errors. * @return * A pointer to a URelativeDateTimeFormatter object for the specified locale, * or NULL if an error occurred. * @stable ICU 57 */ U_STABLE URelativeDateTimeFormatter* U_EXPORT2 ureldatefmt_open( const char* locale, UNumberFormat* nfToAdopt, UDateRelativeDateTimeFormatterStyle width, UDisplayContext capitalizationContext, UErrorCode* status ); /** * Close a URelativeDateTimeFormatter object. Once closed it may no longer be used. * @param reldatefmt * The URelativeDateTimeFormatter object to close. * @stable ICU 57 */ U_STABLE void U_EXPORT2 ureldatefmt_close(URelativeDateTimeFormatter *reldatefmt); #ifndef U_HIDE_DRAFT_API struct UFormattedRelativeDateTime; /** * Opaque struct to contain the results of a URelativeDateTimeFormatter operation. * @draft ICU 64 */ typedef struct UFormattedRelativeDateTime UFormattedRelativeDateTime; /** * Creates an object to hold the result of a URelativeDateTimeFormatter * operation. The object can be used repeatedly; it is cleared whenever * passed to a format function. * * @param ec Set if an error occurs. * @return A pointer needing ownership. * @draft ICU 64 */ U_DRAFT UFormattedRelativeDateTime* U_EXPORT2 ureldatefmt_openResult(UErrorCode* ec); /** * Returns a representation of a UFormattedRelativeDateTime as a UFormattedValue, * which can be subsequently passed to any API requiring that type. * * The returned object is owned by the UFormattedRelativeDateTime and is valid * only as long as the UFormattedRelativeDateTime is present and unchanged in memory. * * You can think of this method as a cast between types. * * @param ufrdt The object containing the formatted string. * @param ec Set if an error occurs. * @return A UFormattedValue owned by the input object. * @draft ICU 64 */ U_DRAFT const UFormattedValue* U_EXPORT2 ureldatefmt_resultAsValue(const UFormattedRelativeDateTime* ufrdt, UErrorCode* ec); /** * Releases the UFormattedRelativeDateTime created by ureldatefmt_openResult. * * @param ufrdt The object to release. * @draft ICU 64 */ U_DRAFT void U_EXPORT2 ureldatefmt_closeResult(UFormattedRelativeDateTime* ufrdt); #endif /* U_HIDE_DRAFT_API */ #if U_SHOW_CPLUSPLUS_API U_NAMESPACE_BEGIN /** * \class LocalURelativeDateTimeFormatterPointer * "Smart pointer" class, closes a URelativeDateTimeFormatter via ureldatefmt_close(). * For most methods see the LocalPointerBase base class. * * @see LocalPointerBase * @see LocalPointer * @stable ICU 57 */ U_DEFINE_LOCAL_OPEN_POINTER(LocalURelativeDateTimeFormatterPointer, URelativeDateTimeFormatter, ureldatefmt_close); #ifndef U_HIDE_DRAFT_API /** * \class LocalUFormattedRelativeDateTimePointer * "Smart pointer" class, closes a UFormattedRelativeDateTime via ureldatefmt_closeResult(). * For most methods see the LocalPointerBase base class. * * @see LocalPointerBase * @see LocalPointer * @draft ICU 64 */ U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedRelativeDateTimePointer, UFormattedRelativeDateTime, ureldatefmt_closeResult); #endif /* U_HIDE_DRAFT_API */ U_NAMESPACE_END #endif /** * Format a combination of URelativeDateTimeUnit and numeric * offset using a numeric style, e.g. "1 week ago", "in 1 week", * "5 weeks ago", "in 5 weeks". * * @param reldatefmt * The URelativeDateTimeFormatter object specifying the * format conventions. * @param offset * The signed offset for the specified unit. This will * be formatted according to this object's UNumberFormat * object. * @param unit * The unit to use when formatting the relative * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param status * A pointer to a UErrorCode to receive any errors. In * case of error status, the contents of result are * undefined. * @return * The length of the formatted result; may be greater * than resultCapacity, in which case an error is returned. * @stable ICU 57 */ U_STABLE int32_t U_EXPORT2 ureldatefmt_formatNumeric( const URelativeDateTimeFormatter* reldatefmt, double offset, URelativeDateTimeUnit unit, UChar* result, int32_t resultCapacity, UErrorCode* status); #ifndef U_HIDE_DRAFT_API /** * Format a combination of URelativeDateTimeUnit and numeric * offset using a numeric style, e.g. "1 week ago", "in 1 week", * "5 weeks ago", "in 5 weeks". * * @param reldatefmt * The URelativeDateTimeFormatter object specifying the * format conventions. * @param offset * The signed offset for the specified unit. This will * be formatted according to this object's UNumberFormat * object. * @param unit * The unit to use when formatting the relative * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. * @param result * A pointer to a UFormattedRelativeDateTime to populate. * @param status * A pointer to a UErrorCode to receive any errors. In * case of error status, the contents of result are * undefined. * @draft ICU 64 */ U_DRAFT void U_EXPORT2 ureldatefmt_formatNumericToResult( const URelativeDateTimeFormatter* reldatefmt, double offset, URelativeDateTimeUnit unit, UFormattedRelativeDateTime* result, UErrorCode* status); #endif /* U_HIDE_DRAFT_API */ /** * Format a combination of URelativeDateTimeUnit and numeric offset * using a text style if possible, e.g. "last week", "this week", * "next week", "yesterday", "tomorrow". Falls back to numeric * style if no appropriate text term is available for the specified * offset in the object's locale. * * @param reldatefmt * The URelativeDateTimeFormatter object specifying the * format conventions. * @param offset * The signed offset for the specified unit. * @param unit * The unit to use when formatting the relative * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param status * A pointer to a UErrorCode to receive any errors. In * case of error status, the contents of result are * undefined. * @return * The length of the formatted result; may be greater * than resultCapacity, in which case an error is returned. * @stable ICU 57 */ U_STABLE int32_t U_EXPORT2 ureldatefmt_format( const URelativeDateTimeFormatter* reldatefmt, double offset, URelativeDateTimeUnit unit, UChar* result, int32_t resultCapacity, UErrorCode* status); #ifndef U_HIDE_DRAFT_API /** * Format a combination of URelativeDateTimeUnit and numeric offset * using a text style if possible, e.g. "last week", "this week", * "next week", "yesterday", "tomorrow". Falls back to numeric * style if no appropriate text term is available for the specified * offset in the object's locale. * * This method populates a UFormattedRelativeDateTime, which exposes more * information than the string populated by format(). * * @param reldatefmt * The URelativeDateTimeFormatter object specifying the * format conventions. * @param offset * The signed offset for the specified unit. * @param unit * The unit to use when formatting the relative * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. * @param result * A pointer to a UFormattedRelativeDateTime to populate. * @param status * A pointer to a UErrorCode to receive any errors. In * case of error status, the contents of result are * undefined. * @draft ICU 64 */ U_DRAFT void U_EXPORT2 ureldatefmt_formatToResult( const URelativeDateTimeFormatter* reldatefmt, double offset, URelativeDateTimeUnit unit, UFormattedRelativeDateTime* result, UErrorCode* status); #endif /* U_HIDE_DRAFT_API */ /** * Combines a relative date string and a time string in this object's * locale. This is done with the same date-time separator used for the * default calendar in this locale to produce a result such as * "yesterday at 3:45 PM". * * @param reldatefmt * The URelativeDateTimeFormatter object specifying the format conventions. * @param relativeDateString * The relative date string. * @param relativeDateStringLen * The length of relativeDateString; may be -1 if relativeDateString * is zero-terminated. * @param timeString * The time string. * @param timeStringLen * The length of timeString; may be -1 if timeString is zero-terminated. * @param result * A pointer to a buffer to receive the formatted result. * @param resultCapacity * The maximum size of result. * @param status * A pointer to a UErrorCode to receive any errors. In case of error status, * the contents of result are undefined. * @return * The length of the formatted result; may be greater than resultCapacity, * in which case an error is returned. * @stable ICU 57 */ U_STABLE int32_t U_EXPORT2 ureldatefmt_combineDateAndTime( const URelativeDateTimeFormatter* reldatefmt, const UChar * relativeDateString, int32_t relativeDateStringLen, const UChar * timeString, int32_t timeStringLen, UChar* result, int32_t resultCapacity, UErrorCode* status ); #endif /* !UCONFIG_NO_FORMATTING && !UCONFIG_NO_BREAK_ITERATION */ #endif PK ! ! measure.hnu [ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ********************************************************************** * Copyright (c) 2004-2015, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: April 26, 2004 * Since: ICU 3.0 ********************************************************************** */ #ifndef __MEASURE_H__ #define __MEASURE_H__ #include "unicode/utypes.h" /** * \file * \brief C++ API: MeasureUnit object. */ #if !UCONFIG_NO_FORMATTING #include "unicode/fmtable.h" U_NAMESPACE_BEGIN class MeasureUnit; /** * An amount of a specified unit, consisting of a number and a Unit. * For example, a length measure consists of a number and a length * unit, such as feet or meters. * *
Measure objects are formatted by MeasureFormat. * *
Measure objects are immutable. * * @author Alan Liu * @stable ICU 3.0 */ class U_I18N_API Measure: public UObject { public: /** * Construct an object with the given numeric amount and the given * unit. After this call, the caller must not delete the given * unit object. * @param number a numeric object; amount.isNumeric() must be TRUE * @param adoptedUnit the unit object, which must not be NULL * @param ec input-output error code. If the amount or the unit * is invalid, then this will be set to a failing value. * @stable ICU 3.0 */ Measure(const Formattable& number, MeasureUnit* adoptedUnit, UErrorCode& ec); /** * Copy constructor * @stable ICU 3.0 */ Measure(const Measure& other); /** * Assignment operator * @stable ICU 3.0 */ Measure& operator=(const Measure& other); /** * Return a polymorphic clone of this object. The result will * have the same class as returned by getDynamicClassID(). * @stable ICU 3.0 */ virtual UObject* clone() const; /** * Destructor * @stable ICU 3.0 */ virtual ~Measure(); /** * Equality operator. Return true if this object is equal * to the given object. * @stable ICU 3.0 */ UBool operator==(const UObject& other) const; /** * Return a reference to the numeric value of this object. The * numeric value may be of any numeric type supported by * Formattable. * @stable ICU 3.0 */ inline const Formattable& getNumber() const; /** * Return a reference to the unit of this object. * @stable ICU 3.0 */ inline const MeasureUnit& getUnit() const; /** * Return the class ID for this class. This is useful only for comparing to * a return value from getDynamicClassID(). For example: *
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
*
* @return The class ID for all objects of this class.
* @stable ICU 53
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 53
*/
virtual UClassID getDynamicClassID(void) const;
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
Measure();
private:
/**
* The numeric value of this object, e.g. 2.54 or 100.
*/
Formattable number;
/**
* The unit of this object, e.g., "millimeter" or "JPY". This is
* owned by this object.
*/
MeasureUnit* unit;
};
inline const Formattable& Measure::getNumber() const {
return number;
}
inline const MeasureUnit& Measure::getUnit() const {
return *unit;
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif // __MEASURE_H__
PK ! rܮw w numberrangeformatter.hnu [ // © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#if !UCONFIG_NO_FORMATTING
#ifndef __NUMBERRANGEFORMATTER_H__
#define __NUMBERRANGEFORMATTER_H__
#include * Usage example: *
*
* NumberRangeFormatter::with()
* .identityFallback(UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE)
* .numberFormatterFirst(NumberFormatter::with().adoptUnit(MeasureUnit::createMeter()))
* .numberFormatterSecond(NumberFormatter::with().adoptUnit(MeasureUnit::createKilometer()))
* .locale("en-GB")
* .formatRange(750, 1.2, status)
* .toString(status);
* // => "750 m - 1.2 km"
*
*
* Like NumberFormatter, NumberRangeFormatter instances (i.e., LocalizedNumberRangeFormatter
* and UnlocalizedNumberRangeFormatter) are immutable and thread-safe. This API is based on the
* fluent design pattern popularized by libraries such as Google's Guava.
*
* @author Shane Carr
*/
/**
* Defines how to merge fields that are identical across the range sign.
*
* @draft ICU 63
*/
typedef enum UNumberRangeCollapse {
/**
* Use locale data and heuristics to determine how much of the string to collapse. Could end up collapsing none,
* some, or all repeated pieces in a locale-sensitive way.
*
* The heuristics used for this option are subject to change over time.
*
* @draft ICU 63
*/
UNUM_RANGE_COLLAPSE_AUTO,
/**
* Do not collapse any part of the number. Example: "3.2 thousand kilograms – 5.3 thousand kilograms"
*
* @draft ICU 63
*/
UNUM_RANGE_COLLAPSE_NONE,
/**
* Collapse the unit part of the number, but not the notation, if present. Example: "3.2 thousand – 5.3 thousand
* kilograms"
*
* @draft ICU 63
*/
UNUM_RANGE_COLLAPSE_UNIT,
/**
* Collapse any field that is equal across the range sign. May introduce ambiguity on the magnitude of the
* number. Example: "3.2 – 5.3 thousand kilograms"
*
* @draft ICU 63
*/
UNUM_RANGE_COLLAPSE_ALL
} UNumberRangeCollapse;
/**
* Defines the behavior when the two numbers in the range are identical after rounding. To programmatically detect
* when the identity fallback is used, compare the lower and upper BigDecimals via FormattedNumber.
*
* @draft ICU 63
* @see NumberRangeFormatter
*/
typedef enum UNumberRangeIdentityFallback {
/**
* Show the number as a single value rather than a range. Example: "$5"
*
* @draft ICU 63
*/
UNUM_IDENTITY_FALLBACK_SINGLE_VALUE,
/**
* Show the number using a locale-sensitive approximation pattern. If the numbers were the same before rounding,
* show the single value. Example: "~$5" or "$5"
*
* @draft ICU 63
*/
UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE,
/**
* Show the number using a locale-sensitive approximation pattern. Use the range pattern always, even if the
* inputs are the same. Example: "~$5"
*
* @draft ICU 63
*/
UNUM_IDENTITY_FALLBACK_APPROXIMATELY,
/**
* Show the number as the range of two equal values. Use the range pattern always, even if the inputs are the
* same. Example (with RangeCollapse.NONE): "$5 – $5"
*
* @draft ICU 63
*/
UNUM_IDENTITY_FALLBACK_RANGE
} UNumberRangeIdentityFallback;
/**
* Used in the result class FormattedNumberRange to indicate to the user whether the numbers formatted in the range
* were equal or not, and whether or not the identity fallback was applied.
*
* @draft ICU 63
* @see NumberRangeFormatter
*/
typedef enum UNumberRangeIdentityResult {
/**
* Used to indicate that the two numbers in the range were equal, even before any rounding rules were applied.
*
* @draft ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_EQUAL_BEFORE_ROUNDING,
/**
* Used to indicate that the two numbers in the range were equal, but only after rounding rules were applied.
*
* @draft ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_EQUAL_AFTER_ROUNDING,
/**
* Used to indicate that the two numbers in the range were not equal, even after rounding rules were applied.
*
* @draft ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_NOT_EQUAL,
#ifndef U_HIDE_INTERNAL_API
/**
* The number of entries in this enum.
* @internal
*/
UNUM_IDENTITY_RESULT_COUNT
#endif
} UNumberRangeIdentityResult;
U_NAMESPACE_BEGIN
namespace number { // icu::number
// Forward declarations:
class UnlocalizedNumberRangeFormatter;
class LocalizedNumberRangeFormatter;
class FormattedNumberRange;
namespace impl {
// Forward declarations:
struct RangeMacroProps;
class DecimalQuantity;
class UFormattedNumberRangeData;
class NumberRangeFormatterImpl;
} // namespace impl
/**
* \cond
* Export an explicit template instantiation. See datefmt.h
* (When building DLLs for Windows this is required.)
*/
#if U_PLATFORM == U_PF_WINDOWS && !defined(U_IN_DOXYGEN)
} // namespace icu::number
U_NAMESPACE_END
template struct U_I18N_API std::atomic< U_NAMESPACE_QUALIFIER number::impl::NumberRangeFormatterImpl*>;
U_NAMESPACE_BEGIN
namespace number { // icu::number
#endif
/** \endcond */
// Other helper classes would go here, but there are none.
namespace impl { // icu::number::impl
// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
/** @internal */
struct U_I18N_API RangeMacroProps : public UMemory {
/** @internal */
UnlocalizedNumberFormatter formatter1; // = NumberFormatter::with();
/** @internal */
UnlocalizedNumberFormatter formatter2; // = NumberFormatter::with();
/** @internal */
bool singleFormatter = true;
/** @internal */
UNumberRangeCollapse collapse = UNUM_RANGE_COLLAPSE_AUTO;
/** @internal */
UNumberRangeIdentityFallback identityFallback = UNUM_IDENTITY_FALLBACK_APPROXIMATELY;
/** @internal */
Locale locale;
// NOTE: Uses default copy and move constructors.
/**
* Check all members for errors.
* @internal
*/
bool copyErrorTo(UErrorCode &status) const {
return formatter1.copyErrorTo(status) || formatter2.copyErrorTo(status);
}
};
} // namespace impl
/**
* An abstract base class for specifying settings related to number formatting. This class is implemented by
* {@link UnlocalizedNumberRangeFormatter} and {@link LocalizedNumberRangeFormatter}. This class is not intended for
* public subclassing.
*/
template
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @draft ICU 63
*/
Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) const &;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @draft ICU 63
*/
Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) &&;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @draft ICU 63
*/
Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) const &;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @draft ICU 63
*/
Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) &&;
/**
* Sets the NumberFormatter instance to use for the first number in the range.
*
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @draft ICU 63
*/
Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) const &;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @draft ICU 63
*/
Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) &&;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @draft ICU 63
*/
Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) const &;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @draft ICU 63
*/
Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) &&;
/**
* Sets the NumberFormatter instance to use for the second number in the range.
*
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @draft ICU 63
*/
Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) const &;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @draft ICU 63
*/
Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) &&;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @draft ICU 63
*/
Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) const &;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @draft ICU 63
*/
Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) &&;
/**
* Sets the aggressiveness of "collapsing" fields across the range separator. Possible values:
*
*
* The default value is AUTO.
*
* @param collapse
* The collapsing strategy to use for this range.
* @return The fluent chain.
* @draft ICU 63
*/
Derived collapse(UNumberRangeCollapse collapse) const &;
/**
* Overload of collapse() for use on an rvalue reference.
*
* @param collapse
* The collapsing strategy to use for this range.
* @return The fluent chain.
* @see #collapse
* @draft ICU 63
*/
Derived collapse(UNumberRangeCollapse collapse) &&;
/**
* Sets the behavior when the two sides of the range are the same. This could happen if the same two numbers are
* passed to the formatRange function, or if different numbers are passed to the function but they become the same
* after rounding rules are applied. Possible values:
*
*
* The default value is APPROXIMATELY.
*
* @param identityFallback
* The strategy to use when formatting two numbers that end up being the same.
* @return The fluent chain.
* @draft ICU 63
*/
Derived identityFallback(UNumberRangeIdentityFallback identityFallback) const &;
/**
* Overload of identityFallback() for use on an rvalue reference.
*
* @param identityFallback
* The strategy to use when formatting two numbers that end up being the same.
* @return The fluent chain.
* @see #identityFallback
* @draft ICU 63
*/
Derived identityFallback(UNumberRangeIdentityFallback identityFallback) &&;
/**
* Returns the current (Un)LocalizedNumberRangeFormatter 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)LocalizedNumberRangeFormatter pointer, or a wrapped
* nullptr on failure.
* @draft ICU 64
*/
LocalPointer An implicit aspect of the For a subclass to support metadata, typical behavior of
* Subclasses must ensure that if the text between start and
* limit is equal to the replacement text, that replace has no
* effect. That is, any metadata
* should be unaffected. In addition, subclasses are encouraged to
* check for initial and trailing identical characters, and make a
* smaller replacement if possible. This will preserve as much
* metadata as possible.
* @param start the beginning index, inclusive; IMPORTANT: New users are strongly encouraged to see if
* numberformatter.h fits their use case. Although not deprecated, this header
* is provided for backwards compatibility only.
*
* Abstract base class for all number formats. Provides interface for
* formatting and parsing a number. Also provides methods for
* determining which locales have number formats, and what their names
* are.
*
* \headerfile unicode/numfmt.h "unicode/numfmt.h"
*
* NumberFormat helps you to format and parse numbers for any locale.
* Your code can be completely independent of the locale conventions
* for decimal points, thousands-separators, or even the particular
* decimal digits used, or whether the number format is even decimal.
*
* To format a number for the current Locale, use one of the static
* factory methods:
* \code
* #include
* If you are formatting multiple numbers, it is more efficient to get
* the format and use it multiple times so that the system doesn't
* have to fetch the information about the local language and country
* conventions multiple times.
* \code
* UnicodeString myString;
* UErrorCode success = U_ZERO_ERROR;
* NumberFormat *nf = NumberFormat::createInstance( success );
* for (int32_t number: {123, 3333, -1234567}) {
* nf->format(number, myString);
* myString += "; ";
* }
* cout << " Example 2: " << myString << endl;
* \endcode
* To format a number for a different Locale, specify it in the
* call to \c createInstance().
* \code
* nf = NumberFormat::createInstance(Locale::getFrench(), success);
* \endcode
* You can use a \c NumberFormat to parse also.
* \code
* UErrorCode success;
* Formattable result(-999); // initialized with error code
* nf->parse(myString, result, success);
* \endcode
* Use \c createInstance() to get the normal number format for a \c Locale.
* There are other static factory methods available. Use \c createCurrencyInstance()
* to get the currency number format for that country. Use \c createPercentInstance()
* to get a format for displaying percentages. With this format, a
* fraction from 0.53 is displayed as 53%.
*
* The type of number formatting can be specified by passing a 'style' parameter to \c createInstance().
* For example, use\n
* \c createInstance(locale, UNUM_DECIMAL, errorCode) to get the normal number format,\n
* \c createInstance(locale, UNUM_PERCENT, errorCode) to get a format for displaying percentage,\n
* \c createInstance(locale, UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,\n
* \c createInstance(locale, UNUM_CURRENCY, errorCode) to get the currency number format,
* in which the currency is represented by its symbol, for example, "$3.00".\n
* \c createInstance(locale, UNUM_CURRENCY_ISO, errorCode) to get the currency number format,
* in which the currency is represented by its ISO code, for example "USD3.00".\n
* \c createInstance(locale, UNUM_CURRENCY_PLURAL, errorCode) to get the currency number format,
* in which the currency is represented by its full name in plural format,
* for example, "3.00 US dollars" or "1.00 US dollar".
*
* You can also control the display of numbers with such methods as
* \c getMinimumFractionDigits(). If you want even more control over the
* format or parsing, or want to give your users more control, you can
* try dynamic_casting the \c NumberFormat you get from the factory methods to a
* \c DecimalFormat. This will work for the vast majority of
* countries; just remember to test for NULL in case you
* encounter an unusual one.
*
* You can also use forms of the parse and format methods with
* \c ParsePosition and \c FieldPosition to allow you to:
*
* If you are using a monospaced font with spacing for alignment, you
* can pass the \c FieldPosition in your format call, with field =
* \c UNUM_INTEGER_FIELD. On output, \c getEndIndex will be set to the offset
* between the last character of the integer and the decimal. Add
* (desiredSpaceCount - getEndIndex) spaces at the front of the
* string.
*
* If you are using proportional fonts, instead of padding with
* spaces, measure the width of the string in pixels from the start to
* getEndIndex. Then move the pen by (desiredPixelWidth -
* widthToAlignmentPoint) before drawing the text. It also works
* where there is no decimal, but possibly additional characters at
* the end, e.g. with parentheses in negative numbers: "(12)" for -12.
*
* User subclasses are not supported. While clients may write
* subclasses, such code will not necessarily work and will not be
* guaranteed to work stably from release to release.
*
* @stable ICU 2.0
*/
class U_I18N_API NumberFormat : public Format {
public:
/**
* Rounding mode.
*
*
* For more detail on rounding modes, see:
* http://userguide.icu-project.org/formatparse/numbers/rounding-modes
*
* @stable ICU 2.4
*/
enum ERoundingMode {
kRoundCeiling, /**< Round towards positive infinity */
kRoundFloor, /**< Round towards negative infinity */
kRoundDown, /**< Round towards zero */
kRoundUp, /**< Round away from zero */
kRoundHalfEven, /**< Round towards the nearest integer, or
towards the nearest even integer if equidistant */
kRoundHalfDown, /**< Round towards the nearest integer, or
towards zero if equidistant */
kRoundHalfUp, /**< Round towards the nearest integer, or
away from zero if equidistant */
/**
* Return U_FORMAT_INEXACT_ERROR if number does not format exactly.
* @stable ICU 4.8
*/
kRoundUnnecessary
};
/**
* Alignment Field constants used to construct a FieldPosition object.
* Signifies that the position of the integer part or fraction part of
* a formatted number should be returned.
*
* Note: as of ICU 4.4, the values in this enum have been extended to
* support identification of all number format fields, not just those
* pertaining to alignment.
*
* These constants are provided for backwards compatibility only.
* Please use the C style constants defined in the header file unum.h.
*
* @see FieldPosition
* @stable ICU 2.0
*/
enum EAlignmentFields {
/** @stable ICU 2.0 */
kIntegerField = UNUM_INTEGER_FIELD,
/** @stable ICU 2.0 */
kFractionField = UNUM_FRACTION_FIELD,
/** @stable ICU 2.0 */
kDecimalSeparatorField = UNUM_DECIMAL_SEPARATOR_FIELD,
/** @stable ICU 2.0 */
kExponentSymbolField = UNUM_EXPONENT_SYMBOL_FIELD,
/** @stable ICU 2.0 */
kExponentSignField = UNUM_EXPONENT_SIGN_FIELD,
/** @stable ICU 2.0 */
kExponentField = UNUM_EXPONENT_FIELD,
/** @stable ICU 2.0 */
kGroupingSeparatorField = UNUM_GROUPING_SEPARATOR_FIELD,
/** @stable ICU 2.0 */
kCurrencyField = UNUM_CURRENCY_FIELD,
/** @stable ICU 2.0 */
kPercentField = UNUM_PERCENT_FIELD,
/** @stable ICU 2.0 */
kPermillField = UNUM_PERMILL_FIELD,
/** @stable ICU 2.0 */
kSignField = UNUM_SIGN_FIELD,
#ifndef U_HIDE_DRAFT_API
/** @draft ICU 64 */
kMeasureUnitField = UNUM_MEASURE_UNIT_FIELD,
/** @draft ICU 64 */
kCompactField = UNUM_COMPACT_FIELD,
#endif // U_HIDE_DRAFT_API
/**
* These constants are provided for backwards compatibility only.
* Please use the constants defined in the header file unum.h.
*/
/** @stable ICU 2.0 */
INTEGER_FIELD = UNUM_INTEGER_FIELD,
/** @stable ICU 2.0 */
FRACTION_FIELD = UNUM_FRACTION_FIELD
};
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~NumberFormat();
/**
* Return true if the given Format objects are semantically equal.
* Objects of different subclasses are considered unequal.
* @return true if the given Format objects are semantically equal.
* @stable ICU 2.0
*/
virtual UBool operator==(const Format& other) const;
using Format::format;
/**
* Format an object to produce a string. This method handles
* Formattable objects with numeric types. If the Formattable
* object type is not a numeric type, then it returns a failing
* UErrorCode.
*
* @param obj The object to format.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Format an object to produce a string. This method handles
* Formattable objects with numeric types. If the Formattable
* object type is not a numeric type, then it returns a failing
* UErrorCode.
*
* @param obj The object to format.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call. Can be
* NULL.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Parse a string to produce an object. This methods handles
* parsing of numeric strings into Formattable objects with numeric
* types.
*
* Before calling, set parse_pos.index to the offset you want to
* start parsing at in the source. After calling, parse_pos.index
* indicates the position after the successfully parsed text. If
* an error occurs, parse_pos.index is unchanged.
*
* When parsing, leading whitespace is discarded (with successful
* parse), while trailing whitespace is left as is.
*
* See Format::parseObject() for more.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parse_pos The position to start parsing at. Upon return
* this param is set to the position after the
* last character successfully parsed. If the
* source is not parsed successfully, this param
* will remain unchanged.
* @return A newly created Formattable* object, or NULL
* on failure. The caller owns this and should
* delete it when done.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const;
/**
* Format a double number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( double number,
UnicodeString& appendTo) const;
/**
* Format a long number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( int32_t number,
UnicodeString& appendTo) const;
/**
* Format an int64 number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.8
*/
UnicodeString& format( int64_t number,
UnicodeString& appendTo) const;
/**
* Format a double number. Concrete subclasses must implement
* these pure virtual methods.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos) const = 0;
/**
* Format a double number. By default, the parent function simply
* calls the base class and does not return an error status.
* Therefore, the status may be ignored in some subclasses.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status error status
* @return Reference to 'appendTo' parameter.
* @internal
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode &status) const;
/**
* Format a double number. Subclasses must implement
* this method.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* Can be NULL.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Format a long number. Concrete subclasses must implement
* these pure virtual methods.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos) const = 0;
/**
* Format a long number. Concrete subclasses may override
* this function to provide status return.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status the output status.
* @return Reference to 'appendTo' parameter.
* @internal
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode &status) const;
/**
* Format an int32 number. Subclasses must implement
* this method.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* Can be NULL.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Format an int64 number. (Not abstract to retain compatibility
* with earlier releases, however subclasses should override this
* method as it just delegates to format(int32_t number...);
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.8
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPosition& pos) const;
/**
* Format an int64 number. (Not abstract to retain compatibility
* with earlier releases, however subclasses should override this
* method as it just delegates to format(int32_t number...);
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @internal
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Format an int64 number. Subclasses must implement
* this method.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* Can be NULL.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Format a decimal number. Subclasses must implement
* this method. The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @param number The unformatted number, as a string, to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* Can be NULL.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(StringPiece number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
// Can't use #ifndef U_HIDE_INTERNAL_API because these are virtual methods
/**
* Format a decimal number.
* The number is a DecimalQuantity wrapper onto a floating point decimal number.
* The default implementation in NumberFormat converts the decimal number
* to a double and formats that. Subclasses of NumberFormat that want
* to specifically handle big decimal numbers must override this method.
* class DecimalFormat does so.
*
* @param number The number, a DecimalQuantity format Decimal Floating Point.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @internal
*/
virtual UnicodeString& format(const number::impl::DecimalQuantity &number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Format a decimal number.
* The number is a DecimalQuantity wrapper onto a floating point decimal number.
* The default implementation in NumberFormat converts the decimal number
* to a double and formats that. Subclasses of NumberFormat that want
* to specifically handle big decimal numbers must override this method.
* class DecimalFormat does so.
*
* @param number The number, a DecimalQuantity format Decimal Floating Point.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @internal
*/
virtual UnicodeString& format(const number::impl::DecimalQuantity &number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Return a long if possible (e.g. within range LONG_MAX,
* LONG_MAX], and with no decimals), otherwise a double. If
* IntegerOnly is set, will stop at a decimal point (or equivalent;
* e.g. for rational numbers "1 2/3", will stop after the 1).
*
* If no object can be parsed, index is unchanged, and NULL is
* returned.
*
* This is a pure virtual which concrete subclasses must implement.
*
* @param text The text to be parsed.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parsePosition The position to start parsing at on input.
* On output, moved to after the last successfully
* parse character. On parse failure, does not change.
* @stable ICU 2.0
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const = 0;
/**
* Parse a string as a numeric value, and return a Formattable
* numeric object. This method parses integers only if IntegerOnly
* is set.
*
* @param text The text to be parsed.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param status Output parameter set to a failure error code
* when a failure occurs.
* @see NumberFormat::isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
UErrorCode& status) const;
/**
* Parses text from the given string as a currency amount. Unlike
* the parse() method, this method will attempt to parse a generic
* currency name, searching for a match of this object's locale's
* currency display names, or for a 3-letter ISO currency code.
* This method will fail if this format is not a currency format,
* that is, if it does not contain the currency pattern symbol
* (U+00A4) in its prefix or suffix.
*
* @param text the string to parse
* @param pos input-output position; on input, the position within text
* to match; must have 0 <= pos.getIndex() < text.length();
* on output, the position after the last matched character.
* If the parse fails, the position in unchanged upon output.
* @return if parse succeeds, a pointer to a newly-created CurrencyAmount
* object (owned by the caller) containing information about
* the parsed currency; if parse fails, this is NULL.
* @stable ICU 49
*/
virtual CurrencyAmount* parseCurrency(const UnicodeString& text,
ParsePosition& pos) const;
/**
* Return true if this format will parse numbers as integers
* only. For example in the English locale, with ParseIntegerOnly
* true, the string "1234." would be parsed as the integer value
* 1234 and parsing would stop at the "." character. Of course,
* the exact format accepted by the parse operation is locale
* dependant and determined by sub-classes of NumberFormat.
* @return true if this format will parse numbers as integers
* only.
* @stable ICU 2.0
*/
UBool isParseIntegerOnly(void) const;
/**
* Sets whether or not numbers should be parsed as integers only.
* @param value set True, this format will parse numbers as integers
* only.
* @see isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void setParseIntegerOnly(UBool value);
/**
* Sets whether lenient parsing should be enabled (it is off by default).
*
* @param enable \c TRUE if lenient parsing should be used,
* \c FALSE otherwise.
* @stable ICU 4.8
*/
virtual void setLenient(UBool enable);
/**
* Returns whether lenient parsing is enabled (it is off by default).
*
* @return \c TRUE if lenient parsing is enabled,
* \c FALSE otherwise.
* @see #setLenient
* @stable ICU 4.8
*/
virtual UBool isLenient(void) const;
/**
* Create a default style NumberFormat for the current default locale.
* The default formatting style is locale dependent.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
/**
* Create a default style NumberFormat for the specified locale.
* The default formatting style is locale dependent.
* @param inLocale the given locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
UErrorCode&);
/**
* Create a specific style NumberFormat for the specified locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param desiredLocale the given locale.
* @param style the given style.
* @param errorCode Output param filled with success/failure status.
* @return A new NumberFormat instance.
* @stable ICU 4.8
*/
static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale,
UNumberFormatStyle style,
UErrorCode& errorCode);
#ifndef U_HIDE_INTERNAL_API
/**
* ICU use only.
* Creates NumberFormat instance without using the cache.
* @internal
*/
static NumberFormat* internalCreateInstance(
const Locale& desiredLocale,
UNumberFormatStyle style,
UErrorCode& errorCode);
/**
* ICU use only.
* Returns handle to the shared, cached NumberFormat instance for given
* locale. On success, caller must call removeRef() on returned value
* once it is done with the shared instance.
* @internal
*/
static const SharedNumberFormat* U_EXPORT2 createSharedInstance(
const Locale& inLocale, UNumberFormatStyle style, UErrorCode& status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Returns a currency format for the current default locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
/**
* Returns a currency format for the specified locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
UErrorCode&);
/**
* Returns a percentage format for the current default locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
/**
* Returns a percentage format for the specified locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
UErrorCode&);
/**
* Returns a scientific format for the current default locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
/**
* Returns a scientific format for the specified locale.
*
* NOTE: New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
UErrorCode&);
/**
* Get the set of Locales for which NumberFormats are installed.
* @param count Output param to receive the size of the locales
* @stable ICU 2.0
*/
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
#if !UCONFIG_NO_SERVICE
/**
* Register a new NumberFormatFactory. The factory will be adopted.
* Because ICU may choose to cache NumberFormat objects internally,
* this must be called at application startup, prior to any calls to
* NumberFormat::createInstance to avoid undefined behavior.
* @param toAdopt the NumberFormatFactory instance to be adopted
* @param status the in/out status code, no special meanings are assigned
* @return a registry key that can be used to unregister this factory
* @stable ICU 2.6
*/
static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
/**
* Unregister a previously-registered NumberFormatFactory using the key returned from the
* register call. Key becomes invalid after a successful call and should not be used again.
* The NumberFormatFactory corresponding to the key will be deleted.
* Because ICU may choose to cache NumberFormat objects internally,
* this should be called during application shutdown, after all calls to
* NumberFormat::createInstance to avoid undefined behavior.
* @param key the registry key returned by a previous call to registerFactory
* @param status the in/out status code, no special meanings are assigned
* @return TRUE if the factory for the key was successfully unregistered
* @stable ICU 2.6
*/
static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
/**
* Return a StringEnumeration over the locales available at the time of the call,
* including registered locales.
* @return a StringEnumeration over the locales available at the time of the call
* @stable ICU 2.6
*/
static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
#endif /* UCONFIG_NO_SERVICE */
/**
* Returns true if grouping is used in this format. For example,
* in the English locale, with grouping on, the number 1234567
* might be formatted as "1,234,567". The grouping separator as
* well as the size of each group is locale dependent and is
* determined by sub-classes of NumberFormat.
* @see setGroupingUsed
* @stable ICU 2.0
*/
UBool isGroupingUsed(void) const;
/**
* Set whether or not grouping will be used in this format.
* @param newValue True, grouping will be used in this format.
* @see getGroupingUsed
* @stable ICU 2.0
*/
virtual void setGroupingUsed(UBool newValue);
/**
* Returns the maximum number of digits allowed in the integer portion of a
* number.
* @return the maximum number of digits allowed in the integer portion of a
* number.
* @see setMaximumIntegerDigits
* @stable ICU 2.0
*/
int32_t getMaximumIntegerDigits(void) const;
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
* new value for maximumIntegerDigits is less than the current value
* of minimumIntegerDigits, then minimumIntegerDigits will also be set to
* the new value.
*
* @param newValue the new value for the maximum number of digits
* allowed in the integer portion of a number.
* @see getMaximumIntegerDigits
* @stable ICU 2.0
*/
virtual void setMaximumIntegerDigits(int32_t newValue);
/**
* Returns the minimum number of digits allowed in the integer portion of a
* number.
* @return the minimum number of digits allowed in the integer portion of a
* number.
* @see setMinimumIntegerDigits
* @stable ICU 2.0
*/
int32_t getMinimumIntegerDigits(void) const;
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
* new value for minimumIntegerDigits exceeds the current value
* of maximumIntegerDigits, then maximumIntegerDigits will also be set to
* the new value.
* @param newValue the new value to be set.
* @see getMinimumIntegerDigits
* @stable ICU 2.0
*/
virtual void setMinimumIntegerDigits(int32_t newValue);
/**
* Returns the maximum number of digits allowed in the fraction portion of a
* number.
* @return the maximum number of digits allowed in the fraction portion of a
* number.
* @see setMaximumFractionDigits
* @stable ICU 2.0
*/
int32_t getMaximumFractionDigits(void) const;
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number. maximumFractionDigits must be >= minimumFractionDigits. If the
* new value for maximumFractionDigits is less than the current value
* of minimumFractionDigits, then minimumFractionDigits will also be set to
* the new value.
* @param newValue the new value to be set.
* @see getMaximumFractionDigits
* @stable ICU 2.0
*/
virtual void setMaximumFractionDigits(int32_t newValue);
/**
* Returns the minimum number of digits allowed in the fraction portion of a
* number.
* @return the minimum number of digits allowed in the fraction portion of a
* number.
* @see setMinimumFractionDigits
* @stable ICU 2.0
*/
int32_t getMinimumFractionDigits(void) const;
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number. minimumFractionDigits must be <= maximumFractionDigits. If the
* new value for minimumFractionDigits exceeds the current value
* of maximumFractionDigits, then maximumIntegerDigits will also be set to
* the new value
* @param newValue the new value to be set.
* @see getMinimumFractionDigits
* @stable ICU 2.0
*/
virtual void setMinimumFractionDigits(int32_t newValue);
/**
* Sets the currency used to display currency
* amounts. This takes effect immediately, if this format is a
* currency format. If this format is not a currency format, then
* the currency is used if and when this object becomes a
* currency format.
* @param theCurrency a 3-letter ISO code indicating new currency
* to use. It need not be null-terminated. May be the empty
* string or NULL to indicate no currency.
* @param ec input-output error code
* @stable ICU 3.0
*/
virtual void setCurrency(const char16_t* theCurrency, UErrorCode& ec);
/**
* Gets the currency used to display currency
* amounts. This may be an empty string for some subclasses.
* @return a 3-letter null-terminated ISO code indicating
* the currency in use, or a pointer to the empty string.
* @stable ICU 2.6
*/
const char16_t* getCurrency() const;
/**
* Set a particular UDisplayContext value in the formatter, such as
* UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
* @param value The UDisplayContext value to set.
* @param status Input/output status. If at entry this indicates a failure
* status, the function will do nothing; otherwise this will be
* updated with any new status from the function.
* @stable ICU 53
*/
virtual void setContext(UDisplayContext value, UErrorCode& status);
/**
* Get the formatter's UDisplayContext value for the specified UDisplayContextType,
* such as UDISPCTX_TYPE_CAPITALIZATION.
* @param type The UDisplayContextType whose value to return
* @param status Input/output status. If at entry this indicates a failure
* status, the function will do nothing; otherwise this will be
* updated with any new status from the function.
* @return The UDisplayContextValue for the specified type.
* @stable ICU 53
*/
virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const;
/**
* Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary
* if the subclass does not support rounding.
* @return A rounding mode
* @stable ICU 60
*/
virtual ERoundingMode getRoundingMode(void) const;
/**
* Set the rounding mode. If a subclass does not support rounding, this will do nothing.
* @param roundingMode A rounding mode
* @stable ICU 60
*/
virtual void setRoundingMode(ERoundingMode roundingMode);
public:
/**
* Return the class ID for this class. This is useful for
* comparing to a return value from getDynamicClassID(). Note that,
* because NumberFormat is an abstract base class, no fully constructed object
* will have the class ID returned by NumberFormat::getStaticClassID().
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
* This method is to implement a simple version of RTTI, since not all
* C++ compilers support genuine RTTI. Polymorphic operator==() and
* clone() methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID(void) const = 0;
protected:
/**
* Default constructor for subclass use only.
* @stable ICU 2.0
*/
NumberFormat();
/**
* Copy constructor.
* @stable ICU 2.0
*/
NumberFormat(const NumberFormat&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
NumberFormat& operator=(const NumberFormat&);
/**
* Returns the currency in effect for this formatter. Subclasses
* should override this method as needed. Unlike getCurrency(),
* this method should never return "".
* @result output parameter for null-terminated result, which must
* have a capacity of at least 4
* @internal
*/
virtual void getEffectiveCurrency(char16_t* result, UErrorCode& ec) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Creates the specified number format style of the desired locale.
* If mustBeDecimalFormat is TRUE, then the returned pointer is
* either a DecimalFormat or it is NULL.
* @internal
*/
static NumberFormat* makeInstance(const Locale& desiredLocale,
UNumberFormatStyle style,
UBool mustBeDecimalFormat,
UErrorCode& errorCode);
#endif /* U_HIDE_INTERNAL_API */
private:
static UBool isStyleSupported(UNumberFormatStyle style);
/**
* Creates the specified decimal format style of the desired locale.
* @param desiredLocale the given locale.
* @param style the given style.
* @param errorCode Output param filled with success/failure status.
* @return A new NumberFormat instance.
*/
static NumberFormat* makeInstance(const Locale& desiredLocale,
UNumberFormatStyle style,
UErrorCode& errorCode);
UBool fGroupingUsed;
int32_t fMaxIntegerDigits;
int32_t fMinIntegerDigits;
int32_t fMaxFractionDigits;
int32_t fMinFractionDigits;
protected:
/** \internal */
static const int32_t gDefaultMaxIntegerDigits;
/** \internal */
static const int32_t gDefaultMinIntegerDigits;
private:
UBool fParseIntegerOnly;
UBool fLenient; // TRUE => lenient parse is enabled
// ISO currency code
char16_t fCurrency[4];
UDisplayContext fCapitalizationContext;
friend class ICUNumberFormatFactory; // access to makeInstance
friend class ICUNumberFormatService;
friend class ::NumberFormatTest; // access to isStyleSupported()
};
#if !UCONFIG_NO_SERVICE
/**
* A NumberFormatFactory is used to register new number formats. The factory
* should be able to create any of the predefined formats for each locale it
* supports. When registered, the locales it supports extend or override the
* locale already supported by ICU.
*
* @stable ICU 2.6
*/
class U_I18N_API NumberFormatFactory : public UObject {
public:
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~NumberFormatFactory();
/**
* Return true if this factory will be visible. Default is true.
* If not visible, the locales supported by this factory will not
* be listed by getAvailableLocales.
* @stable ICU 2.6
*/
virtual UBool visible(void) const = 0;
/**
* Return the locale names directly supported by this factory. The number of names
* is returned in count;
* @stable ICU 2.6
*/
virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0;
/**
* Return a number format of the appropriate type. If the locale
* is not supported, return null. If the locale is supported, but
* the type is not provided by this service, return null. Otherwise
* return an appropriate instance of NumberFormat.
* @stable ICU 2.6
*/
virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0;
};
/**
* A NumberFormatFactory that supports a single locale. It can be visible or invisible.
* @stable ICU 2.6
*/
class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory {
protected:
/**
* True if the locale supported by this factory is visible.
* @stable ICU 2.6
*/
const UBool _visible;
/**
* The locale supported by this factory, as a UnicodeString.
* @stable ICU 2.6
*/
UnicodeString _id;
public:
/**
* @stable ICU 2.6
*/
SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE);
/**
* @stable ICU 3.0
*/
virtual ~SimpleNumberFormatFactory();
/**
* @stable ICU 2.6
*/
virtual UBool visible(void) const;
/**
* @stable ICU 2.6
*/
virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const;
};
#endif /* #if !UCONFIG_NO_SERVICE */
// -------------------------------------
inline UBool
NumberFormat::isParseIntegerOnly() const
{
return fParseIntegerOnly;
}
inline UBool
NumberFormat::isLenient() const
{
return fLenient;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _NUMFMT
//eof
PK ! O
*
*
*
*
* FieldPosition fpos(UNUM_INTEGER_FIELD);
* while (formattedNumberRange.nextFieldPosition(fpos, status)) {
* // do something with fpos.
* }
*
*
* This method is useful if you know which field to query. If you want all available field position
* information, use #getAllFieldPositions().
*
* @param fieldPosition
* Input+output variable. See {@link FormattedNumber#nextFieldPosition}.
* @param status
* Set if an error occurs while populating the FieldPosition.
* @return TRUE if a new occurrence of the field was found; FALSE otherwise.
* @draft ICU 63
* @see UNumberFormatFields
*/
UBool nextFieldPosition(FieldPosition& fieldPosition, UErrorCode& status) const;
/**
* Export the formatted number range to a FieldPositionIterator. This allows you to determine which characters in
* the output string correspond to which fields, such as the integer part, fraction part, and sign.
*
* If information on only one field is needed, use #nextFieldPosition() instead.
*
* @param iterator
* The FieldPositionIterator to populate with all of the fields present in the formatted number.
* @param status
* Set if an error occurs while populating the FieldPositionIterator.
* @draft ICU 63
* @see UNumberFormatFields
*/
void getAllFieldPositions(FieldPositionIterator &iterator, UErrorCode &status) const;
/**
* Export the first formatted number as a decimal number. This endpoint
* is useful for obtaining the exact number being printed after scaling
* and rounding have been applied by the number range formatting pipeline.
*
* The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @return A decimal representation of the first formatted number.
* @draft ICU 63
* @see NumberRangeFormatter
* @see #getSecondDecimal
*/
UnicodeString getFirstDecimal(UErrorCode& status) const;
/**
* Export the second formatted number as a decimal number. This endpoint
* is useful for obtaining the exact number being printed after scaling
* and rounding have been applied by the number range formatting pipeline.
*
* The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @return A decimal representation of the second formatted number.
* @draft ICU 63
* @see NumberRangeFormatter
* @see #getFirstDecimal
*/
UnicodeString getSecondDecimal(UErrorCode& status) const;
/**
* Returns whether the pair of numbers was successfully formatted as a range or whether an identity fallback was
* used. For example, if the first and second number were the same either before or after rounding occurred, an
* identity fallback was used.
*
* @return An indication the resulting identity situation in the formatted number range.
* @draft ICU 63
* @see UNumberRangeIdentityFallback
*/
UNumberRangeIdentityResult getIdentityResult(UErrorCode& status) const;
/**
* Copying not supported; use move constructor instead.
*/
FormattedNumberRange(const FormattedNumberRange&) = delete;
/**
* Copying not supported; use move assignment instead.
*/
FormattedNumberRange& operator=(const FormattedNumberRange&) = delete;
/**
* Move constructor:
* Leaves the source FormattedNumberRange in an undefined state.
* @draft ICU 63
*/
FormattedNumberRange(FormattedNumberRange&& src) U_NOEXCEPT;
/**
* Move assignment:
* Leaves the source FormattedNumberRange in an undefined state.
* @draft ICU 63
*/
FormattedNumberRange& operator=(FormattedNumberRange&& src) U_NOEXCEPT;
/**
* Destruct an instance of FormattedNumberRange, cleaning up any memory it might own.
* @draft ICU 63
*/
~FormattedNumberRange();
private:
// Can't use LocalPointer because UFormattedNumberRangeData is forward-declared
const impl::UFormattedNumberRangeData *fData;
// Error code for the terminal methods
UErrorCode fErrorCode;
/**
* Internal constructor from data type. Adopts the data pointer.
* @internal
*/
explicit FormattedNumberRange(impl::UFormattedNumberRangeData *results)
: fData(results), fErrorCode(U_ZERO_ERROR) {}
explicit FormattedNumberRange(UErrorCode errorCode)
: fData(nullptr), fErrorCode(errorCode) {}
void getAllFieldPositionsImpl(FieldPositionIteratorHandler& fpih, UErrorCode& status) const;
// To give LocalizedNumberRangeFormatter format methods access to this class's constructor:
friend class LocalizedNumberRangeFormatter;
};
/**
* See the main description in numberrangeformatter.h for documentation and examples.
*
* @draft ICU 63
*/
class U_I18N_API NumberRangeFormatter final {
public:
/**
* Call this method at the beginning of a NumberRangeFormatter fluent chain in which the locale is not currently
* known at the call site.
*
* @return An {@link UnlocalizedNumberRangeFormatter}, to be used for chaining.
* @draft ICU 63
*/
static UnlocalizedNumberRangeFormatter with();
/**
* Call this method at the beginning of a NumberRangeFormatter 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 range formatting.
* @return A {@link LocalizedNumberRangeFormatter}, to be used for chaining.
* @draft ICU 63
*/
static LocalizedNumberRangeFormatter withLocale(const Locale &locale);
/**
* Use factory methods instead of the constructor to create a NumberFormatter.
*/
NumberRangeFormatter() = delete;
};
} // namespace number
U_NAMESPACE_END
#endif // U_HIDE_DRAFT_API
#endif // __NUMBERRANGEFORMATTER_H__
#endif /* #if !UCONFIG_NO_FORMATTING */
PK ! }AT AT ucharstrie.hnu [ // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2010-2012, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* file name: ucharstrie.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2010nov14
* created by: Markus W. Scherer
*/
#ifndef __UCHARSTRIE_H__
#define __UCHARSTRIE_H__
/**
* \file
* \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences)
* to integer values.
*/
#include "unicode/utypes.h"
#include "unicode/unistr.h"
#include "unicode/uobject.h"
#include "unicode/ustringtrie.h"
U_NAMESPACE_BEGIN
class Appendable;
class UCharsTrieBuilder;
class UVector32;
/**
* Light-weight, non-const reader class for a UCharsTrie.
* Traverses a char16_t-serialized data structure with minimal state,
* for mapping strings (16-bit-unit sequences) to non-negative integer values.
*
* This class owns the serialized trie data only if it was constructed by
* the builder's build() method.
* The public constructor and the copy constructor only alias the data (only copy the pointer).
* There is no assignment operator.
*
* This class is not intended for public subclassing.
* @stable ICU 4.8
*/
class U_COMMON_API UCharsTrie : public UMemory {
public:
/**
* Constructs a UCharsTrie reader instance.
*
* The trieUChars must contain a copy of a char16_t sequence from the UCharsTrieBuilder,
* starting with the first char16_t of that sequence.
* The UCharsTrie object will not read more char16_ts than
* the UCharsTrieBuilder generated in the corresponding build() call.
*
* The array is not copied/cloned and must not be modified while
* the UCharsTrie object is in use.
*
* @param trieUChars The char16_t array that contains the serialized trie.
* @stable ICU 4.8
*/
UCharsTrie(ConstChar16Ptr trieUChars)
: ownedArray_(NULL), uchars_(trieUChars),
pos_(uchars_), remainingMatchLength_(-1) {}
/**
* Destructor.
* @stable ICU 4.8
*/
~UCharsTrie();
/**
* Copy constructor, copies the other trie reader object and its state,
* but not the char16_t array which will be shared. (Shallow copy.)
* @param other Another UCharsTrie object.
* @stable ICU 4.8
*/
UCharsTrie(const UCharsTrie &other)
: ownedArray_(NULL), uchars_(other.uchars_),
pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}
/**
* Resets this trie to its initial state.
* @return *this
* @stable ICU 4.8
*/
UCharsTrie &reset() {
pos_=uchars_;
remainingMatchLength_=-1;
return *this;
}
/**
* UCharsTrie state object, for saving a trie's current state
* and resetting the trie back to this state later.
* @stable ICU 4.8
*/
class State : public UMemory {
public:
/**
* Constructs an empty State.
* @stable ICU 4.8
*/
State() { uchars=NULL; }
private:
friend class UCharsTrie;
const char16_t *uchars;
const char16_t *pos;
int32_t remainingMatchLength;
};
/**
* Saves the state of this trie.
* @param state The State object to hold the trie's state.
* @return *this
* @see resetToState
* @stable ICU 4.8
*/
const UCharsTrie &saveState(State &state) const {
state.uchars=uchars_;
state.pos=pos_;
state.remainingMatchLength=remainingMatchLength_;
return *this;
}
/**
* Resets this trie to the saved state.
* If the state object contains no state, or the state of a different trie,
* then this trie remains unchanged.
* @param state The State object which holds a saved trie state.
* @return *this
* @see saveState
* @see reset
* @stable ICU 4.8
*/
UCharsTrie &resetToState(const State &state) {
if(uchars_==state.uchars && uchars_!=NULL) {
pos_=state.pos;
remainingMatchLength_=state.remainingMatchLength;
}
return *this;
}
/**
* Determines whether the string so far matches, whether it has a value,
* and whether another input char16_t can continue a matching string.
* @return The match/value Result.
* @stable ICU 4.8
*/
UStringTrieResult current() const;
/**
* Traverses the trie from the initial state for this input char16_t.
* Equivalent to reset().next(uchar).
* @param uchar Input char value. Values below 0 and above 0xffff will never match.
* @return The match/value Result.
* @stable ICU 4.8
*/
inline UStringTrieResult first(int32_t uchar) {
remainingMatchLength_=-1;
return nextImpl(uchars_, uchar);
}
/**
* Traverses the trie from the initial state for the
* one or two UTF-16 code units for this input code point.
* Equivalent to reset().nextForCodePoint(cp).
* @param cp A Unicode code point 0..0x10ffff.
* @return The match/value Result.
* @stable ICU 4.8
*/
UStringTrieResult firstForCodePoint(UChar32 cp);
/**
* Traverses the trie from the current state for this input char16_t.
* @param uchar Input char value. Values below 0 and above 0xffff will never match.
* @return The match/value Result.
* @stable ICU 4.8
*/
UStringTrieResult next(int32_t uchar);
/**
* Traverses the trie from the current state for the
* one or two UTF-16 code units for this input code point.
* @param cp A Unicode code point 0..0x10ffff.
* @return The match/value Result.
* @stable ICU 4.8
*/
UStringTrieResult nextForCodePoint(UChar32 cp);
/**
* Traverses the trie from the current state for this string.
* Equivalent to
* \code
* Result result=current();
* for(each c in s)
* if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;
* result=next(c);
* return result;
* \endcode
* @param s A string. Can be NULL if length is 0.
* @param length The length of the string. Can be -1 if NUL-terminated.
* @return The match/value Result.
* @stable ICU 4.8
*/
UStringTrieResult next(ConstChar16Ptr s, int32_t length);
/**
* Returns a matching string's value if called immediately after
* current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE.
* getValue() can be called multiple times.
*
* Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!
* @return The value for the string so far.
* @stable ICU 4.8
*/
inline int32_t getValue() const {
const char16_t *pos=pos_;
int32_t leadUnit=*pos++;
// U_ASSERT(leadUnit>=kMinValueLead);
return leadUnit&kValueIsFinal ?
readValue(pos, leadUnit&0x7fff) : readNodeValue(pos, leadUnit);
}
/**
* Determines whether all strings reachable from the current state
* map to the same value.
* @param uniqueValue Receives the unique value, if this function returns TRUE.
* (output-only)
* @return TRUE if all strings reachable from the current state
* map to the same value.
* @stable ICU 4.8
*/
inline UBool hasUniqueValue(int32_t &uniqueValue) const {
const char16_t *pos=pos_;
// Skip the rest of a pending linear-match node.
return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue);
}
/**
* Finds each char16_t which continues the string from the current state.
* That is, each char16_t c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now.
* @param out Each next char16_t is appended to this object.
* @return the number of char16_ts which continue the string from here
* @stable ICU 4.8
*/
int32_t getNextUChars(Appendable &out) const;
/**
* Iterator for all of the (string, value) pairs in a UCharsTrie.
* @stable ICU 4.8
*/
class U_COMMON_API Iterator : public UMemory {
public:
/**
* Iterates from the root of a char16_t-serialized UCharsTrie.
* @param trieUChars The trie char16_ts.
* @param maxStringLength If 0, the iterator returns full strings.
* Otherwise, the iterator returns strings with this maximum length.
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @stable ICU 4.8
*/
Iterator(ConstChar16Ptr trieUChars, int32_t maxStringLength, UErrorCode &errorCode);
/**
* Iterates from the current state of the specified UCharsTrie.
* @param trie The trie whose state will be copied for iteration.
* @param maxStringLength If 0, the iterator returns full strings.
* Otherwise, the iterator returns strings with this maximum length.
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @stable ICU 4.8
*/
Iterator(const UCharsTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);
/**
* Destructor.
* @stable ICU 4.8
*/
~Iterator();
/**
* Resets this iterator to its initial state.
* @return *this
* @stable ICU 4.8
*/
Iterator &reset();
/**
* @return TRUE if there are more elements.
* @stable ICU 4.8
*/
UBool hasNext() const;
/**
* Finds the next (string, value) pair if there is one.
*
* If the string is truncated to the maximum length and does not
* have a real value, then the value is set to -1.
* In this case, this "not a real value" is indistinguishable from
* a real value of -1.
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @return TRUE if there is another element.
* @stable ICU 4.8
*/
UBool next(UErrorCode &errorCode);
/**
* @return The string for the last successful next().
* @stable ICU 4.8
*/
const UnicodeString &getString() const { return str_; }
/**
* @return The value for the last successful next().
* @stable ICU 4.8
*/
int32_t getValue() const { return value_; }
private:
UBool truncateAndStop() {
pos_=NULL;
value_=-1; // no real value for str
return TRUE;
}
const char16_t *branchNext(const char16_t *pos, int32_t length, UErrorCode &errorCode);
const char16_t *uchars_;
const char16_t *pos_;
const char16_t *initialPos_;
int32_t remainingMatchLength_;
int32_t initialRemainingMatchLength_;
UBool skipValue_; // Skip intermediate value which was already delivered.
UnicodeString str_;
int32_t maxLength_;
int32_t value_;
// The stack stores pairs of integers for backtracking to another
// outbound edge of a branch node.
// The first integer is an offset from uchars_.
// The second integer has the str_.length() from before the node in bits 15..0,
// and the remaining branch length in bits 31..16.
// (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit,
// but the code looks more confusing that way.)
UVector32 *stack_;
};
private:
friend class UCharsTrieBuilder;
/**
* Constructs a UCharsTrie reader instance.
* Unlike the public constructor which just aliases an array,
* this constructor adopts the builder's array.
* This constructor is only called by the builder.
*/
UCharsTrie(char16_t *adoptUChars, const char16_t *trieUChars)
: ownedArray_(adoptUChars), uchars_(trieUChars),
pos_(uchars_), remainingMatchLength_(-1) {}
// No assignment operator.
UCharsTrie &operator=(const UCharsTrie &other);
inline void stop() {
pos_=NULL;
}
// Reads a compact 32-bit integer.
// pos is already after the leadUnit, and the lead unit has bit 15 reset.
static inline int32_t readValue(const char16_t *pos, int32_t leadUnit) {
int32_t value;
if(leadUnitReplaceable is an abstract base class representing a
* string of characters that supports the replacement of a range of
* itself with a new string of characters. It is used by APIs that
* change a piece of text while retaining metadata. Metadata is data
* other than the Unicode characters returned by char32At(). One
* example of metadata is style attributes; another is an edit
* history, marking each character with an author and revision number.
*
* Replaceable API is that
* during a replace operation, new characters take on the metadata of
* the old characters. For example, if the string "the bold
* font" has range (4, 8) replaced with "strong", then it becomes "the
* strong font".
*
* Replaceable specifies ranges using a start
* offset and a limit offset. The range of characters thus specified
* includes the characters at offset start..limit-1. That is, the
* start offset is inclusive, and the limit offset is exclusive.
*
* Replaceable also includes API to access characters
* in the string: length(), charAt(),
* char32At(), and extractBetween().
*
* replace() is the following:
*
*
* If this is not the behavior, the subclass should document any differences.
* @author Alan Liu
* @stable ICU 2.0
*/
class U_COMMON_API Replaceable : public UObject {
public:
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~Replaceable();
/**
* Returns the number of 16-bit code units in the text.
* @return number of 16-bit code units in text
* @stable ICU 1.8
*/
inline int32_t length() const;
/**
* Returns the 16-bit code unit at the given offset into the text.
* @param offset an integer between 0 and
* length()-1
* inclusive
* @return 16-bit code unit of text at given offset
* @stable ICU 1.8
*/
inline char16_t charAt(int32_t offset) const;
/**
* Returns the 32-bit code point at the given 16-bit offset into
* the text. This assumes the text is stored as 16-bit code units
* with surrogate pairs intermixed. If the offset of a leading or
* trailing code unit of a surrogate pair is given, return the
* code point of the surrogate pair.
*
* @param offset an integer between 0 and length()-1
* inclusive
* @return 32-bit code point of text at given offset
* @stable ICU 1.8
*/
inline UChar32 char32At(int32_t offset) const;
/**
* Copies characters in the range [start, limit)
* into the UnicodeString target.
* @param start offset of first character which will be copied
* @param limit offset immediately following the last character to
* be copied
* @param target UnicodeString into which to copy characters.
* @return A reference to target
* @stable ICU 2.1
*/
virtual void extractBetween(int32_t start,
int32_t limit,
UnicodeString& target) const = 0;
/**
* Replaces a substring of this object with the given text. If the
* characters being replaced have metadata, the new characters
* that replace them should be given the same metadata.
*
* 0 <= start
* <= limit.
* @param limit the ending index, exclusive; start <= limit
* <= length().
* @param text the text to replace characters start
* to limit - 1
* @stable ICU 2.0
*/
virtual void handleReplaceBetween(int32_t start,
int32_t limit,
const UnicodeString& text) = 0;
// Note: All other methods in this class take the names of
// existing UnicodeString methods. This method is the exception.
// It is named differently because all replace methods of
// UnicodeString return a UnicodeString&. The 'between' is
// required in order to conform to the UnicodeString naming
// convention; API taking start/length are named 0 <= start <=
* limit.
* @param limit the ending index, exclusive; start <= limit <=
* length().
* @param dest the destination index. The characters from
* start..limit-1 will be copied to dest.
* Implementations of this method may assume that dest <= start ||
* dest >= limit.
* @stable ICU 2.0
*/
virtual void copy(int32_t start, int32_t limit, int32_t dest) = 0;
/**
* Returns true if this object contains metadata. If a
* Replaceable object has metadata, calls to the Replaceable API
* must be made so as to preserve metadata. If it does not, calls
* to the Replaceable API may be optimized to improve performance.
* The default implementation returns true.
* @return true if this object contains metadata
* @stable ICU 2.2
*/
virtual UBool hasMetaData() const;
/**
* Clone this object, an instance of a subclass of Replaceable.
* Clones can be used concurrently in multiple threads.
* If a subclass does not implement clone(), or if an error occurs,
* then NULL is returned.
* The clone functions in all subclasses return a pointer to a Replaceable
* because some compilers do not support covariant (same-as-this)
* return types; cast to the appropriate subclass if necessary.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.6
*/
virtual Replaceable *clone() const;
protected:
/**
* Default constructor.
* @stable ICU 2.4
*/
inline Replaceable();
/*
* Assignment operator not declared. The compiler will provide one
* which does nothing since this class does not contain any data members.
* API/code coverage may show the assignment operator as present and
* untested - ignore.
* Subclasses need this assignment operator if they use compiler-provided
* assignment operators of their own. An alternative to not declaring one
* here would be to declare and empty-implement a protected or public one.
Replaceable &Replaceable::operator=(const Replaceable &);
*/
/**
* Virtual version of length().
* @stable ICU 2.4
*/
virtual int32_t getLength() const = 0;
/**
* Virtual version of charAt().
* @stable ICU 2.4
*/
virtual char16_t getCharAt(int32_t offset) const = 0;
/**
* Virtual version of char32At().
* @stable ICU 2.4
*/
virtual UChar32 getChar32At(int32_t offset) const = 0;
};
inline Replaceable::Replaceable() {}
inline int32_t
Replaceable::length() const {
return getLength();
}
inline char16_t
Replaceable::charAt(int32_t offset) const {
return getCharAt(offset);
}
inline UChar32
Replaceable::char32At(int32_t offset) const {
return getChar32At(offset);
}
// There is no rep.cpp, see unistr.cpp for Replaceable function implementations.
U_NAMESPACE_END
#endif
PK ! 9b b numfmt.hnu [ // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2016, International Business Machines Corporation and others.
* All Rights Reserved.
********************************************************************************
*
* File NUMFMT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/18/97 clhuang Updated per C++ implementation.
* 04/17/97 aliu Changed DigitCount to int per code review.
* 07/20/98 stephen JDK 1.2 sync up. Added scientific support.
* Changed naming conventions to match C++ guidelines
* Derecated Java style constants (eg, INTEGER_FIELD)
********************************************************************************
*/
#ifndef NUMFMT_H
#define NUMFMT_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Compatibility APIs for number formatting.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/format.h"
#include "unicode/unum.h" // UNumberFormatStyle
#include "unicode/locid.h"
#include "unicode/stringpiece.h"
#include "unicode/curramt.h"
#include "unicode/udisplaycontext.h"
class NumberFormatTest;
U_NAMESPACE_BEGIN
class SharedNumberFormat;
#if !UCONFIG_NO_SERVICE
class NumberFormatFactory;
class StringEnumeration;
#endif
/**
*
*
* For example, you can align numbers in two ways.
*