2 ********************************************************************************
3 * Copyright (C) 1997-2009, International Business Machines Corporation and others.
5 ********************************************************************************
9 * Modification History:
11 * Date Name Description
12 * 02/19/97 aliu Converted from java.
13 * 03/18/97 clhuang Updated per C++ implementation.
14 * 04/17/97 aliu Changed DigitCount to int per code review.
15 * 07/20/98 stephen JDK 1.2 sync up. Added scientific support.
16 * Changed naming conventions to match C++ guidelines
17 * Derecated Java style constants (eg, INTEGER_FIELD)
18 ********************************************************************************
25 #include "unicode/utypes.h"
29 * \brief C++ API: Abstract base class for all number formats.
32 #if !UCONFIG_NO_FORMATTING
34 #include "unicode/unistr.h"
35 #include "unicode/format.h"
36 #include "unicode/unum.h" // UNumberFormatStyle
37 #include "unicode/locid.h"
41 #if !UCONFIG_NO_SERVICE
42 class NumberFormatFactory
;
43 class StringEnumeration
;
48 * Abstract base class for all number formats. Provides interface for
49 * formatting and parsing a number. Also provides methods for
50 * determining which locales have number formats, and what their names
53 * NumberFormat helps you to format and parse numbers for any locale.
54 * Your code can be completely independent of the locale conventions
55 * for decimal points, thousands-separators, or even the particular
56 * decimal digits used, or whether the number format is even decimal.
58 * To format a number for the current Locale, use one of the static
62 * double myNumber = 7.0;
63 * UnicodeString myString;
64 * UErrorCode success = U_ZERO_ERROR;
65 * NumberFormat* nf = NumberFormat::createInstance(success)
66 * nf->format(myNumber, myString);
67 * cout << " Example 1: " << myString << endl;
70 * If you are formatting multiple numbers, it is more efficient to get
71 * the format and use it multiple times so that the system doesn't
72 * have to fetch the information about the local language and country
73 * conventions multiple times.
76 * UnicodeString myString;
77 * UErrorCode success = U_ZERO_ERROR;
78 * nf = NumberFormat::createInstance( success );
79 * int32_t a[] = { 123, 3333, -1234567 };
80 * const int32_t a_len = sizeof(a) / sizeof(a[0]);
82 * for (int32_t i = 0; i < a_len; i++) {
83 * nf->format(a[i], myString);
86 * cout << " Example 2: " << myString << endl;
89 * To format a number for a different Locale, specify it in the
90 * call to createInstance().
93 * nf = NumberFormat::createInstance( Locale::FRENCH, success );
96 * You can use a NumberFormat to parse also.
100 * Formattable result(-999); // initialized with error code
101 * nf->parse(myString, result, success);
104 * Use createInstance to get the normal number format for that country.
105 * There are other static factory methods available. Use getCurrency
106 * to get the currency number format for that country. Use getPercent
107 * to get a format for displaying percentages. With this format, a
108 * fraction from 0.53 is displayed as 53%.
110 * You can also control the display of numbers with such methods as
111 * getMinimumFractionDigits. If you want even more control over the
112 * format or parsing, or want to give your users more control, you can
113 * try casting the NumberFormat you get from the factory methods to a
114 * DecimalNumberFormat. This will work for the vast majority of
115 * countries; just remember to put it in a try block in case you
116 * encounter an unusual one.
118 * You can also use forms of the parse and format methods with
119 * ParsePosition and FieldPosition to allow you to:
121 * <li>(a) progressively parse through pieces of a string.
122 * <li>(b) align the decimal point and other areas.
124 * For example, you can align numbers in two ways.
126 * If you are using a monospaced font with spacing for alignment, you
127 * can pass the FieldPosition in your format call, with field =
128 * INTEGER_FIELD. On output, getEndIndex will be set to the offset
129 * between the last character of the integer and the decimal. Add
130 * (desiredSpaceCount - getEndIndex) spaces at the front of the
133 * If you are using proportional fonts, instead of padding with
134 * spaces, measure the width of the string in pixels from the start to
135 * getEndIndex. Then move the pen by (desiredPixelWidth -
136 * widthToAlignmentPoint) before drawing the text. It also works
137 * where there is no decimal, but possibly additional characters at
138 * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
140 * <em>User subclasses are not supported.</em> While clients may write
141 * subclasses, such code will not necessarily work and will not be
142 * guaranteed to work stably from release to release.
146 class U_I18N_API NumberFormat
: public Format
{
150 * Alignment Field constants used to construct a FieldPosition object.
151 * Signifies that the position of the integer part or fraction part of
152 * a formatted number should be returned.
157 enum EAlignmentFields
{
163 * These constants are provided for backwards compatibility only.
164 * Please use the C++ style constants defined above.
167 INTEGER_FIELD
= kIntegerField
,
168 FRACTION_FIELD
= kFractionField
175 virtual ~NumberFormat();
178 * Return true if the given Format objects are semantically equal.
179 * Objects of different subclasses are considered unequal.
180 * @return true if the given Format objects are semantically equal.
183 virtual UBool
operator==(const Format
& other
) const;
186 * Format an object to produce a string. This method handles
187 * Formattable objects with numeric types. If the Formattable
188 * object type is not a numeric type, then it returns a failing
191 * @param obj The object to format.
192 * @param appendTo Output parameter to receive result.
193 * Result is appended to existing contents.
194 * @param pos On input: an alignment field, if desired.
195 * On output: the offsets of the alignment field.
196 * @param status Output param filled with success/failure status.
197 * @return Reference to 'appendTo' parameter.
200 virtual UnicodeString
& format(const Formattable
& obj
,
201 UnicodeString
& appendTo
,
203 UErrorCode
& status
) const;
206 * Parse a string to produce an object. This methods handles
207 * parsing of numeric strings into Formattable objects with numeric
210 * Before calling, set parse_pos.index to the offset you want to
211 * start parsing at in the source. After calling, parse_pos.index
212 * indicates the position after the successfully parsed text. If
213 * an error occurs, parse_pos.index is unchanged.
215 * When parsing, leading whitespace is discarded (with successful
216 * parse), while trailing whitespace is left as is.
218 * See Format::parseObject() for more.
220 * @param source The string to be parsed into an object.
221 * @param result Formattable to be set to the parse result.
222 * If parse fails, return contents are undefined.
223 * @param parse_pos The position to start parsing at. Upon return
224 * this param is set to the position after the
225 * last character successfully parsed. If the
226 * source is not parsed successfully, this param
227 * will remain unchanged.
228 * @return A newly created Formattable* object, or NULL
229 * on failure. The caller owns this and should
230 * delete it when done.
233 virtual void parseObject(const UnicodeString
& source
,
235 ParsePosition
& parse_pos
) const;
238 * Format a double number. These methods call the NumberFormat
239 * pure virtual format() methods with the default FieldPosition.
241 * @param number The value to be formatted.
242 * @param appendTo Output parameter to receive result.
243 * Result is appended to existing contents.
244 * @return Reference to 'appendTo' parameter.
247 UnicodeString
& format( double number
,
248 UnicodeString
& appendTo
) const;
251 * Format a long number. These methods call the NumberFormat
252 * pure virtual format() methods with the default FieldPosition.
254 * @param number The value to be formatted.
255 * @param appendTo Output parameter to receive result.
256 * Result is appended to existing contents.
257 * @return Reference to 'appendTo' parameter.
260 UnicodeString
& format( int32_t number
,
261 UnicodeString
& appendTo
) const;
264 * Format an int64 number. These methods call the NumberFormat
265 * pure virtual format() methods with the default FieldPosition.
267 * @param number The value to be formatted.
268 * @param appendTo Output parameter to receive result.
269 * Result is appended to existing contents.
270 * @return Reference to 'appendTo' parameter.
273 UnicodeString
& format( int64_t number
,
274 UnicodeString
& appendTo
) const;
277 * Format a double number. Concrete subclasses must implement
278 * these pure virtual methods.
280 * @param number The value to be formatted.
281 * @param appendTo Output parameter to receive result.
282 * Result is appended to existing contents.
283 * @param pos On input: an alignment field, if desired.
284 * On output: the offsets of the alignment field.
285 * @return Reference to 'appendTo' parameter.
288 virtual UnicodeString
& format(double number
,
289 UnicodeString
& appendTo
,
290 FieldPosition
& pos
) const = 0;
292 * Format a long number. Concrete subclasses must implement
293 * these pure virtual methods.
295 * @param number The value to be formatted.
296 * @param appendTo Output parameter to receive result.
297 * Result is appended to existing contents.
298 * @param pos On input: an alignment field, if desired.
299 * On output: the offsets of the alignment field.
300 * @return Reference to 'appendTo' parameter.
303 virtual UnicodeString
& format(int32_t number
,
304 UnicodeString
& appendTo
,
305 FieldPosition
& pos
) const = 0;
308 * Format an int64 number. (Not abstract to retain compatibility
309 * with earlier releases, however subclasses should override this
310 * method as it just delegates to format(int32_t number...);
312 * @param number The value to be formatted.
313 * @param appendTo Output parameter to receive result.
314 * Result is appended to existing contents.
315 * @param pos On input: an alignment field, if desired.
316 * On output: the offsets of the alignment field.
317 * @return Reference to 'appendTo' parameter.
320 virtual UnicodeString
& format(int64_t number
,
321 UnicodeString
& appendTo
,
322 FieldPosition
& pos
) const;
324 * Redeclared Format method.
325 * @param obj The object to be formatted.
326 * @param appendTo Output parameter to receive result.
327 * Result is appended to existing contents.
328 * @param status Output parameter set to a failure error code
329 * when a failure occurs.
330 * @return Reference to 'appendTo' parameter.
333 UnicodeString
& format(const Formattable
& obj
,
334 UnicodeString
& appendTo
,
335 UErrorCode
& status
) const;
338 * Return a long if possible (e.g. within range LONG_MAX,
339 * LONG_MAX], and with no decimals), otherwise a double. If
340 * IntegerOnly is set, will stop at a decimal point (or equivalent;
341 * e.g. for rational numbers "1 2/3", will stop after the 1).
343 * If no object can be parsed, index is unchanged, and NULL is
346 * This is a pure virtual which concrete subclasses must implement.
348 * @param text The text to be parsed.
349 * @param result Formattable to be set to the parse result.
350 * If parse fails, return contents are undefined.
351 * @param parsePosition The position to start parsing at on input.
352 * On output, moved to after the last successfully
353 * parse character. On parse failure, does not change.
354 * @return A Formattable object of numeric type. The caller
355 * owns this an must delete it. NULL on failure.
358 virtual void parse(const UnicodeString
& text
,
360 ParsePosition
& parsePosition
) const = 0;
363 * Parse a string as a numeric value, and return a Formattable
364 * numeric object. This method parses integers only if IntegerOnly
367 * @param text The text to be parsed.
368 * @param result Formattable to be set to the parse result.
369 * If parse fails, return contents are undefined.
370 * @param status Output parameter set to a failure error code
371 * when a failure occurs.
372 * @return A Formattable object of numeric type. The caller
373 * owns this an must delete it. NULL on failure.
374 * @see NumberFormat::isParseIntegerOnly
377 virtual void parse( const UnicodeString
& text
,
379 UErrorCode
& status
) const;
382 * Parses text from the given string as a currency amount. Unlike
383 * the parse() method, this method will attempt to parse a generic
384 * currency name, searching for a match of this object's locale's
385 * currency display names, or for a 3-letter ISO currency code.
386 * This method will fail if this format is not a currency format,
387 * that is, if it does not contain the currency pattern symbol
388 * (U+00A4) in its prefix or suffix.
390 * @param text the string to parse
391 * @param result output parameter to receive result. This will have
392 * its currency set to the parsed ISO currency code.
393 * @param pos input-output position; on input, the position within
394 * text to match; must have 0 <= pos.getIndex() < text.length();
395 * on output, the position after the last matched character. If
396 * the parse fails, the position in unchanged upon output.
397 * @return a reference to result
400 virtual Formattable
& parseCurrency(const UnicodeString
& text
,
402 ParsePosition
& pos
) const;
405 * Return true if this format will parse numbers as integers
406 * only. For example in the English locale, with ParseIntegerOnly
407 * true, the string "1234." would be parsed as the integer value
408 * 1234 and parsing would stop at the "." character. Of course,
409 * the exact format accepted by the parse operation is locale
410 * dependant and determined by sub-classes of NumberFormat.
411 * @return true if this format will parse numbers as integers
415 UBool
isParseIntegerOnly(void) const;
418 * Sets whether or not numbers should be parsed as integers only.
419 * @param value set True, this format will parse numbers as integers
421 * @see isParseIntegerOnly
424 virtual void setParseIntegerOnly(UBool value
);
427 * Return whether or not strict parsing is in effect.
429 * @return <code>TRUE</code> if strict parsing is in effect,
430 * <code>FALSE</code> otherwise.
433 UBool
isParseStrict(void) const;
436 * Set whether or not strict parsing should be used.
438 * @param value <code>TRUE</code> if strict parsing should be used,
439 * <code>FALSE</code> otherwise.
442 virtual void setParseStrict(UBool value
);
445 * Returns the default number format for the current default
446 * locale. The default format is one of the styles provided by
447 * the other factory methods: getNumberInstance,
448 * getCurrencyInstance or getPercentInstance. Exactly which one
449 * is locale dependant.
452 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
455 * Returns the default number format for the specified locale.
456 * The default format is one of the styles provided by the other
457 * factory methods: getNumberInstance, getCurrencyInstance or
458 * getPercentInstance. Exactly which one is locale dependant.
459 * @param inLocale the given locale.
462 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& inLocale
,
466 * Returns a currency format for the current default locale.
469 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
472 * Returns a currency format for the specified locale.
473 * @param inLocale the given locale.
476 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
480 * Returns a percentage format for the current default locale.
483 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
486 * Returns a percentage format for the specified locale.
487 * @param inLocale the given locale.
490 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
494 * Returns a scientific format for the current default locale.
497 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
500 * Returns a scientific format for the specified locale.
501 * @param inLocale the given locale.
504 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
508 * Get the set of Locales for which NumberFormats are installed.
509 * @param count Output param to receive the size of the locales
512 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
514 #if !UCONFIG_NO_SERVICE
516 * Register a new NumberFormatFactory. The factory will be adopted.
517 * @param toAdopt the NumberFormatFactory instance to be adopted
518 * @param status the in/out status code, no special meanings are assigned
519 * @return a registry key that can be used to unregister this factory
522 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
525 * Unregister a previously-registered NumberFormatFactory using the key returned from the
526 * register call. Key becomes invalid after a successful call and should not be used again.
527 * The NumberFormatFactory corresponding to the key will be deleted.
528 * @param key the registry key returned by a previous call to registerFactory
529 * @param status the in/out status code, no special meanings are assigned
530 * @return TRUE if the factory for the key was successfully unregistered
533 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
536 * Return a StringEnumeration over the locales available at the time of the call,
537 * including registered locales.
538 * @return a StringEnumeration over the locales available at the time of the call
541 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
542 #endif /* UCONFIG_NO_SERVICE */
545 * Returns true if grouping is used in this format. For example,
546 * in the English locale, with grouping on, the number 1234567
547 * might be formatted as "1,234,567". The grouping separator as
548 * well as the size of each group is locale dependant and is
549 * determined by sub-classes of NumberFormat.
550 * @see setGroupingUsed
553 UBool
isGroupingUsed(void) const;
556 * Set whether or not grouping will be used in this format.
557 * @param newValue True, grouping will be used in this format.
558 * @see getGroupingUsed
561 virtual void setGroupingUsed(UBool newValue
);
564 * Returns the maximum number of digits allowed in the integer portion of a
566 * @return the maximum number of digits allowed in the integer portion of a
568 * @see setMaximumIntegerDigits
571 int32_t getMaximumIntegerDigits(void) const;
574 * Sets the maximum number of digits allowed in the integer portion of a
575 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
576 * new value for maximumIntegerDigits is less than the current value
577 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
580 * @param newValue the new value for the maximum number of digits
581 * allowed in the integer portion of a number.
582 * @see getMaximumIntegerDigits
585 virtual void setMaximumIntegerDigits(int32_t newValue
);
588 * Returns the minimum number of digits allowed in the integer portion of a
590 * @return the minimum number of digits allowed in the integer portion of a
592 * @see setMinimumIntegerDigits
595 int32_t getMinimumIntegerDigits(void) const;
598 * Sets the minimum number of digits allowed in the integer portion of a
599 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
600 * new value for minimumIntegerDigits exceeds the current value
601 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
603 * @param newValue the new value to be set.
604 * @see getMinimumIntegerDigits
607 virtual void setMinimumIntegerDigits(int32_t newValue
);
610 * Returns the maximum number of digits allowed in the fraction portion of a
612 * @return the maximum number of digits allowed in the fraction portion of a
614 * @see setMaximumFractionDigits
617 int32_t getMaximumFractionDigits(void) const;
620 * Sets the maximum number of digits allowed in the fraction portion of a
621 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
622 * new value for maximumFractionDigits is less than the current value
623 * of minimumFractionDigits, then minimumFractionDigits will also be set to
625 * @param newValue the new value to be set.
626 * @see getMaximumFractionDigits
629 virtual void setMaximumFractionDigits(int32_t newValue
);
632 * Returns the minimum number of digits allowed in the fraction portion of a
634 * @return the minimum number of digits allowed in the fraction portion of a
636 * @see setMinimumFractionDigits
639 int32_t getMinimumFractionDigits(void) const;
642 * Sets the minimum number of digits allowed in the fraction portion of a
643 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
644 * new value for minimumFractionDigits exceeds the current value
645 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
647 * @param newValue the new value to be set.
648 * @see getMinimumFractionDigits
651 virtual void setMinimumFractionDigits(int32_t newValue
);
654 * Sets the currency used to display currency
655 * amounts. This takes effect immediately, if this format is a
656 * currency format. If this format is not a currency format, then
657 * the currency is used if and when this object becomes a
659 * @param theCurrency a 3-letter ISO code indicating new currency
660 * to use. It need not be null-terminated. May be the empty
661 * string or NULL to indicate no currency.
662 * @param ec input-output error code
665 virtual void setCurrency(const UChar
* theCurrency
, UErrorCode
& ec
);
668 * Gets the currency used to display currency
669 * amounts. This may be an empty string for some subclasses.
670 * @return a 3-letter null-terminated ISO code indicating
671 * the currency in use, or a pointer to the empty string.
674 const UChar
* getCurrency() const;
679 * Return the class ID for this class. This is useful for
680 * comparing to a return value from getDynamicClassID(). Note that,
681 * because NumberFormat is an abstract base class, no fully constructed object
682 * will have the class ID returned by NumberFormat::getStaticClassID().
683 * @return The class ID for all objects of this class.
686 static UClassID U_EXPORT2
getStaticClassID(void);
689 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
690 * This method is to implement a simple version of RTTI, since not all
691 * C++ compilers support genuine RTTI. Polymorphic operator==() and
692 * clone() methods call this method.
694 * @return The class ID for this object. All objects of a
695 * given class have the same class ID. Objects of
696 * other classes have different class IDs.
699 virtual UClassID
getDynamicClassID(void) const = 0;
704 * Default constructor for subclass use only.
713 NumberFormat(const NumberFormat
&);
716 * Assignment operator.
719 NumberFormat
& operator=(const NumberFormat
&);
722 * Returns the currency in effect for this formatter. Subclasses
723 * should override this method as needed. Unlike getCurrency(),
724 * this method should never return "".
725 * @result output parameter for null-terminated result, which must
726 * have a capacity of at least 4
729 virtual void getEffectiveCurrency(UChar
* result
, UErrorCode
& ec
) const;
738 kStyleCount
// ALWAYS LAST ENUM: number of styles
742 * Creates the specified decimal format style of the desired locale.
743 * Hook for service registration, uses makeInstance directly if no services
745 * @param desiredLocale the given locale.
746 * @param choice the given style.
747 * @param success Output param filled with success/failure status.
748 * @return A new NumberFormat instance.
750 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
753 * Creates the specified decimal format style of the desired locale.
754 * @param desiredLocale the given locale.
755 * @param choice the given style.
756 * @param success Output param filled with success/failure status.
757 * @return A new NumberFormat instance.
759 static NumberFormat
* makeInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
762 int32_t fMaxIntegerDigits
;
763 int32_t fMinIntegerDigits
;
764 int32_t fMaxFractionDigits
;
765 int32_t fMinFractionDigits
;
766 UBool fParseIntegerOnly
;
772 friend class ICUNumberFormatFactory
; // access to makeInstance, EStyles
773 friend class ICUNumberFormatService
;
776 #if !UCONFIG_NO_SERVICE
778 * A NumberFormatFactory is used to register new number formats. The factory
779 * should be able to create any of the predefined formats for each locale it
780 * supports. When registered, the locales it supports extend or override the
781 * locale already supported by ICU.
785 class U_I18N_API NumberFormatFactory
: public UObject
{
792 virtual ~NumberFormatFactory();
795 * Return true if this factory will be visible. Default is true.
796 * If not visible, the locales supported by this factory will not
797 * be listed by getAvailableLocales.
800 virtual UBool
visible(void) const = 0;
803 * Return the locale names directly supported by this factory. The number of names
804 * is returned in count;
807 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
810 * Return a number format of the appropriate type. If the locale
811 * is not supported, return null. If the locale is supported, but
812 * the type is not provided by this service, return null. Otherwise
813 * return an appropriate instance of NumberFormat.
816 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
820 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
823 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
826 * True if the locale supported by this factory is visible.
829 const UBool _visible
;
832 * The locale supported by this factory, as a UnicodeString.
841 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
846 virtual ~SimpleNumberFormatFactory();
851 virtual UBool
visible(void) const;
856 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
858 #endif /* #if !UCONFIG_NO_SERVICE */
860 // -------------------------------------
863 NumberFormat::isParseIntegerOnly() const
865 return fParseIntegerOnly
;
869 NumberFormat::isParseStrict() const
874 inline UnicodeString
&
875 NumberFormat::format(const Formattable
& obj
,
876 UnicodeString
& appendTo
,
877 UErrorCode
& status
) const {
878 return Format::format(obj
, appendTo
, status
);
883 #endif /* #if !UCONFIG_NO_FORMATTING */