class NumberFormat
Defined at line 175 of file ../../third_party/icu/latest/source/i18n/unicode/numfmt.h
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.
Note that there are additional factory methods within subclasses of
NumberFormat.
<P
>
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.
To format a number for a different Locale, specify it in the
call to
You can use a
to parse also.
Use
to get the normal number format for a
There are other static factory methods available. Use
to get the currency number format for that country. Use
to get a format for displaying percentages. With this format, a
fraction from 0.53 is displayed as 53%.
<P
>
The type of number formatting can be specified by passing a 'style' parameter to
For example, use
UNUM_DECIMAL, errorCode) to get the normal number format,
UNUM_PERCENT, errorCode) to get a format for displaying percentage,
UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,
UNUM_CURRENCY, errorCode) to get the currency number format,
in which the currency is represented by its symbol, for example, "$3.00".
UNUM_CURRENCY_ISO, errorCode) to get the currency number format,
in which the currency is represented by its ISO code, for example "USD3.00".
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".
<P
>
You can also control the display of numbers with such methods as
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
you get from the factory methods to a
This will work for the vast majority of
countries; just remember to test for nullptr in case you
encounter an unusual one.
<P
>
You can also use forms of the parse and format methods with
and
to allow you to:
(a) progressively parse through pieces of a string.
(b) align the decimal point and other areas.
For example, you can align numbers in two ways.
<P
>
If you are using a monospaced font with spacing for alignment, you
can pass the
in your format call, with field =
On output,
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.
<P
>
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.
ICU 2.0
Code
#include <iostream>
#include "unicode/numfmt.h"
#include "unicode/unistr.h"
#include "unicode/ustream.h"
using namespace std;
int main() {
double myNumber = 7.0;
UnicodeString myString;
UErrorCode success = U_ZERO_ERROR;
NumberFormat* nf = NumberFormat::createInstance(success);
nf->format(myNumber, myString);
cout << " Example 1: " << myString << endl;
}
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;
nf = NumberFormat::createInstance(Locale::getFrench(), success);
UErrorCode success;
Formattable result(-999); // initialized with error code
nf->parse(myString, result, success);
Protected Members
static const int32_t gDefaultMaxIntegerDigits
static const int32_t gDefaultMinIntegerDigits
Public Methods
void ~NumberFormat ()
Destructor.
ICU 2.0
NumberFormat * clone ()
Clones this object polymorphically.
The caller owns the result and should delete it when done.
Returns
clone, or nullptr if an error occurred
ICU 2.0
bool operator== (const Format & other)
Return true if the given Format objects are semantically equal.
Objects of different subclasses are considered unequal.
Returns
true if the given Format objects are semantically equal.
ICU 2.0
UnicodeString & format (const Formattable & obj, UnicodeString & appendTo, FieldPosition & pos, UErrorCode & status)
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.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.0
UnicodeString & format (const Formattable & obj, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
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.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 4.4
void parseObject (const UnicodeString & source, Formattable & result, ParsePosition & parse_pos)
Parse a string to produce an object. This methods handles
parsing of numeric strings into Formattable objects with numeric
types.
<P
>
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.
<P
>
When parsing, leading whitespace is discarded (with successful
parse), while trailing whitespace is left as is.
<P
>
See Format::parseObject() for more.
Parameters
Returns
A newly created Formattable* object, or nullptr
on failure. The caller owns this and should
delete it when done.
ICU 2.0
UnicodeString & format (double number, UnicodeString & appendTo)
Format a double number. These methods call the NumberFormat
pure virtual format() methods with the default FieldPosition.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.0
UnicodeString & format (int32_t number, UnicodeString & appendTo)
Format a long number. These methods call the NumberFormat
pure virtual format() methods with the default FieldPosition.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.0
UnicodeString & format (int64_t number, UnicodeString & appendTo)
Format an int64 number. These methods call the NumberFormat
pure virtual format() methods with the default FieldPosition.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.8
UnicodeString & format (double number, UnicodeString & appendTo, FieldPosition & pos)
Format a double number. Concrete subclasses must implement
these pure virtual methods.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.0
UnicodeString & format (double number, UnicodeString & appendTo, FieldPosition & pos, UErrorCode & status)
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.
Parameters
Returns
Reference to 'appendTo' parameter.
UnicodeString & format (double number, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
Format a double number. Subclasses must implement
this method.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 4.4
UnicodeString & format (int32_t number, UnicodeString & appendTo, FieldPosition & pos)
Format a long number. Concrete subclasses must implement
these pure virtual methods.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.0
UnicodeString & format (int32_t number, UnicodeString & appendTo, FieldPosition & pos, UErrorCode & status)
Format a long number. Concrete subclasses may override
this function to provide status return.
Parameters
Returns
Reference to 'appendTo' parameter.
UnicodeString & format (int32_t number, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
Format an int32 number. Subclasses must implement
this method.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 4.4
UnicodeString & format (int64_t number, UnicodeString & appendTo, FieldPosition & pos)
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...);
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 2.8
UnicodeString & format (int64_t number, UnicodeString & appendTo, FieldPosition & pos, UErrorCode & status)
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...);
Parameters
Returns
Reference to 'appendTo' parameter.
UnicodeString & format (int64_t number, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
Format an int64 number. Subclasses must implement
this method.
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 4.4
UnicodeString & format (StringPiece number, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
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
Parameters
Returns
Reference to 'appendTo' parameter.
ICU 4.4
UnicodeString & format (const number::impl::DecimalQuantity & number, UnicodeString & appendTo, FieldPositionIterator * posIter, UErrorCode & status)
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.
Parameters
Returns
Reference to 'appendTo' parameter.
UnicodeString & format (const number::impl::DecimalQuantity & number, UnicodeString & appendTo, FieldPosition & pos, UErrorCode & status)
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.
Parameters
Returns
Reference to 'appendTo' parameter.
void parse (const UnicodeString & text, Formattable & result, ParsePosition & parsePosition)
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).
<P
>
If no object can be parsed, index is unchanged, and nullptr is
returned.
<P
>
This is a pure virtual which concrete subclasses must implement.
Parameters
void parse (const UnicodeString & text, Formattable & result, UErrorCode & status)
Parse a string as a numeric value, and return a Formattable
numeric object. This method parses integers only if IntegerOnly
is set.
Parameters
CurrencyAmount * parseCurrency (const UnicodeString & text, ParsePosition & pos)
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.
Parameters
Returns
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 nullptr.
ICU 49
UBool isParseIntegerOnly ()
-------------------------------------
Defined at line 1267 of file ../../third_party/icu/latest/source/i18n/unicode/numfmt.h
void setParseIntegerOnly (UBool value)
Sets whether or not numbers should be parsed as integers only.
Parameters
void setLenient (UBool enable)
Sets whether lenient parsing should be enabled (it is off by default).
Parameters
UBool isLenient ()
Returns whether lenient parsing is enabled (it is off by default).
Returns
if lenient parsing is enabled,
otherwise.
Defined at line 1273 of file ../../third_party/icu/latest/source/i18n/unicode/numfmt.h
NumberFormat * createInstance (UErrorCode & )
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
{
NumberFormat * createInstance (const Locale & inLocale, UErrorCode & )
Create a default style NumberFormat for the specified locale.
The default formatting style is locale dependent.
Parameters
NumberFormat * createInstance (const Locale & desiredLocale, UNumberFormatStyle style, UErrorCode & errorCode)
Create a specific style NumberFormat for the specified locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * internalCreateInstance (const Locale & desiredLocale, UNumberFormatStyle style, UErrorCode & errorCode)
ICU use only.
Creates NumberFormat instance without using the cache.
const SharedNumberFormat * createSharedInstance (const Locale & inLocale, UNumberFormatStyle style, UErrorCode & status)
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.
NumberFormat * createCurrencyInstance (UErrorCode & )
Returns a currency format for the current default locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * createCurrencyInstance (const Locale & inLocale, UErrorCode & )
Returns a currency format for the specified locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * createPercentInstance (UErrorCode & )
Returns a percentage format for the current default locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * createPercentInstance (const Locale & inLocale, UErrorCode & )
Returns a percentage format for the specified locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * createScientificInstance (UErrorCode & )
Returns a scientific format for the current default locale.
NOTE:
New users are strongly encouraged to use
{
NumberFormat * createScientificInstance (const Locale & inLocale, UErrorCode & )
Returns a scientific format for the specified locale.
NOTE:
New users are strongly encouraged to use
{
const Locale * getAvailableLocales (int32_t & count)
Get the set of Locales for which NumberFormats are installed.
Parameters
URegistryKey registerFactory (NumberFormatFactory * toAdopt, UErrorCode & status)
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.
Parameters
Returns
a registry key that can be used to unregister this factory
ICU 2.6
UBool unregister (URegistryKey key, 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.
Parameters
Returns
true if the factory for the key was successfully unregistered
ICU 2.6
StringEnumeration * getAvailableLocales ()
Return a StringEnumeration over the locales available at the time of the call,
including registered locales.
Returns
a StringEnumeration over the locales available at the time of the call
ICU 2.6
UBool isGroupingUsed ()
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.
void setGroupingUsed (UBool newValue)
Set whether or not grouping will be used in this format.
Parameters
int32_t getMaximumIntegerDigits ()
Returns the maximum number of digits allowed in the integer portion of a
number.
Returns
the maximum number of digits allowed in the integer portion of a
number.
void setMaximumIntegerDigits (int32_t newValue)
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.
Parameters
int32_t getMinimumIntegerDigits ()
Returns the minimum number of digits allowed in the integer portion of a
number.
Returns
the minimum number of digits allowed in the integer portion of a
number.
void setMinimumIntegerDigits (int32_t newValue)
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.
Parameters
int32_t getMaximumFractionDigits ()
Returns the maximum number of digits allowed in the fraction portion of a
number.
Returns
the maximum number of digits allowed in the fraction portion of a
number.
void setMaximumFractionDigits (int32_t newValue)
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.
Parameters
int32_t getMinimumFractionDigits ()
Returns the minimum number of digits allowed in the fraction portion of a
number.
Returns
the minimum number of digits allowed in the fraction portion of a
number.
void setMinimumFractionDigits (int32_t newValue)
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
Parameters
void setCurrency (const char16_t * theCurrency, UErrorCode & ec)
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.
Parameters
const char16_t * getCurrency ()
Gets the currency used to display currency
amounts. This may be an empty string for some subclasses.
Returns
a 3-letter null-terminated ISO code indicating
the currency in use, or a pointer to the empty string.
ICU 2.6
void setContext (UDisplayContext value, UErrorCode & status)
Set a particular UDisplayContext value in the formatter, such as
UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
Parameters
UDisplayContext getContext (UDisplayContextType type, UErrorCode & status)
Get the formatter's UDisplayContext value for the specified UDisplayContextType,
such as UDISPCTX_TYPE_CAPITALIZATION.
Parameters
Returns
The UDisplayContextValue for the specified type.
ICU 53
ERoundingMode getRoundingMode ()
Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary
if the subclass does not support rounding.
Returns
A rounding mode
ICU 60
void setRoundingMode (ERoundingMode roundingMode)
Set the rounding mode. If a subclass does not support rounding, this will do nothing.
Parameters
UClassID getStaticClassID ()
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().
Returns
The class ID for all objects of this class.
ICU 2.0
UClassID getDynamicClassID ()
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.
<P
>
Returns
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.
ICU 2.0
Protected Methods
void NumberFormat ()
Default constructor for subclass use only.
ICU 2.0
void NumberFormat (const NumberFormat & )
Copy constructor.
ICU 2.0
NumberFormat & operator= (const NumberFormat & )
Assignment operator.
ICU 2.0
void getEffectiveCurrency (char16_t * result, UErrorCode & ec)
Returns the currency in effect for this formatter. Subclasses
should override this method as needed. Unlike getCurrency(),
this method should never return "".
NumberFormat * makeInstance (const Locale & desiredLocale, UNumberFormatStyle style, UBool mustBeDecimalFormat, UErrorCode & errorCode)
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 nullptr.
Enumerations
enum ERoundingMode
| Name | Value |
|---|---|
| kRoundCeiling | 0 |
| kRoundFloor | 1 |
| kRoundDown | 2 |
| kRoundUp | 3 |
| kRoundHalfEven | 4 |
| kRoundHalfDown | 5 |
| kRoundHalfUp | 6 |
| kRoundUnnecessary | 7 |
| kRoundHalfOdd | 8 |
| kRoundHalfCeiling | 9 |
| kRoundHalfFloor | 10 |
Rounding mode.
For more detail on rounding modes, see:
https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes
ICU 2.4
Defined at line 186 of file ../../third_party/icu/latest/source/i18n/unicode/numfmt.h
enum EAlignmentFields
| Name | Value |
|---|---|
| kIntegerField | UNUM_INTEGER_FIELD |
| kFractionField | UNUM_FRACTION_FIELD |
| kDecimalSeparatorField | UNUM_DECIMAL_SEPARATOR_FIELD |
| kExponentSymbolField | UNUM_EXPONENT_SYMBOL_FIELD |
| kExponentSignField | UNUM_EXPONENT_SIGN_FIELD |
| kExponentField | UNUM_EXPONENT_FIELD |
| kGroupingSeparatorField | UNUM_GROUPING_SEPARATOR_FIELD |
| kCurrencyField | UNUM_CURRENCY_FIELD |
| kPercentField | UNUM_PERCENT_FIELD |
| kPermillField | UNUM_PERMILL_FIELD |
| kSignField | UNUM_SIGN_FIELD |
| kMeasureUnitField | UNUM_MEASURE_UNIT_FIELD |
| kCompactField | UNUM_COMPACT_FIELD |
| INTEGER_FIELD | UNUM_INTEGER_FIELD |
| FRACTION_FIELD | UNUM_FRACTION_FIELD |
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.
Defined at line 234 of file ../../third_party/icu/latest/source/i18n/unicode/numfmt.h
Friends
class NumberFormatTest
class ICUNumberFormatService
class ICUNumberFormatFactory