2 * Copyright (C) {1997-2004}, International Business Machines Corporation and others. All Rights Reserved.
3 ********************************************************************************
7 * Modification History:
9 * Date Name Description
10 * 02/19/97 aliu Converted from java.
11 * 03/18/97 clhuang Updated per C++ implementation.
12 * 04/17/97 aliu Changed DigitCount to int per code review.
13 * 07/20/98 stephen JDK 1.2 sync up. Added scientific support.
14 * Changed naming conventions to match C++ guidelines
15 * Derecated Java style constants (eg, INTEGER_FIELD)
16 ********************************************************************************
23 #include "unicode/utypes.h"
25 #if !UCONFIG_NO_FORMATTING
27 #include "unicode/unistr.h"
28 #include "unicode/format.h"
29 #include "unicode/unum.h" // UNumberFormatStyle
30 #include "unicode/locid.h"
34 #if !UCONFIG_NO_SERVICE
35 class NumberFormatFactory
;
36 class StringEnumeration
;
41 typedef const void* URegistryKey
;
45 * Abstract base class for all number formats. Provides interface for
46 * formatting and parsing a number. Also provides methods for
47 * determining which locales have number formats, and what their names
50 * NumberFormat helps you to format and parse numbers for any locale.
51 * Your code can be completely independent of the locale conventions
52 * for decimal points, thousands-separators, or even the particular
53 * decimal digits used, or whether the number format is even decimal.
55 * To format a number for the current Locale, use one of the static
59 * double myNumber = 7.0;
60 * UnicodeString myString;
61 * UErrorCode success = U_ZERO_ERROR;
62 * NumberFormat* nf = NumberFormat::createInstance(success)
63 * nf->format(myNumber, myString);
64 * cout << " Example 1: " << myString << endl;
67 * If you are formatting multiple numbers, it is more efficient to get
68 * the format and use it multiple times so that the system doesn't
69 * have to fetch the information about the local language and country
70 * conventions multiple times.
73 * UnicodeString myString;
74 * UErrorCode success = U_ZERO_ERROR;
75 * nf = NumberFormat::createInstance( success );
76 * int32_t a[] = { 123, 3333, -1234567 };
77 * const int32_t a_len = sizeof(a) / sizeof(a[0]);
79 * for (int32_t i = 0; i < a_len; i++) {
80 * nf->format(a[i], myString);
83 * cout << " Example 2: " << myString << endl;
86 * To format a number for a different Locale, specify it in the
87 * call to createInstance().
90 * nf = NumberFormat::createInstance( Locale::FRENCH, success );
93 * You can use a NumberFormat to parse also.
97 * Formattable result(-999); // initialized with error code
98 * nf->parse(myString, result, success);
101 * Use createInstance to get the normal number format for that country.
102 * There are other static factory methods available. Use getCurrency
103 * to get the currency number format for that country. Use getPercent
104 * to get a format for displaying percentages. With this format, a
105 * fraction from 0.53 is displayed as 53%.
107 * You can also control the display of numbers with such methods as
108 * getMinimumFractionDigits. If you want even more control over the
109 * format or parsing, or want to give your users more control, you can
110 * try casting the NumberFormat you get from the factory methods to a
111 * DecimalNumberFormat. This will work for the vast majority of
112 * countries; just remember to put it in a try block in case you
113 * encounter an unusual one.
115 * You can also use forms of the parse and format methods with
116 * ParsePosition and FieldPosition to allow you to:
118 * <li>(a) progressively parse through pieces of a string.
119 * <li>(b) align the decimal point and other areas.
121 * For example, you can align numbers in two ways.
123 * If you are using a monospaced font with spacing for alignment, you
124 * can pass the FieldPosition in your format call, with field =
125 * INTEGER_FIELD. On output, getEndIndex will be set to the offset
126 * between the last character of the integer and the decimal. Add
127 * (desiredSpaceCount - getEndIndex) spaces at the front of the
130 * If you are using proportional fonts, instead of padding with
131 * spaces, measure the width of the string in pixels from the start to
132 * getEndIndex. Then move the pen by (desiredPixelWidth -
133 * widthToAlignmentPoint) before drawing the text. It also works
134 * where there is no decimal, but possibly additional characters at
135 * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
137 * <em>User subclasses are not supported.</em> While clients may write
138 * subclasses, such code will not necessarily work and will not be
139 * guaranteed to work stably from release to release.
143 class U_I18N_API NumberFormat
: public Format
{
147 * Alignment Field constants used to construct a FieldPosition object.
148 * Signifies that the position of the integer part or fraction part of
149 * a formatted number should be returned.
154 enum EAlignmentFields
{
160 * These constants are provided for backwards compatibility only.
161 * Please use the C++ style constants defined above.
164 INTEGER_FIELD
= kIntegerField
,
165 FRACTION_FIELD
= kFractionField
172 virtual ~NumberFormat();
175 * Return true if the given Format objects are semantically equal.
176 * Objects of different subclasses are considered unequal.
177 * @return true if the given Format objects are semantically equal.
180 virtual UBool
operator==(const Format
& other
) const;
183 * Format an object to produce a string. This method handles
184 * Formattable objects with numeric types. If the Formattable
185 * object type is not a numeric type, then it returns a failing
188 * @param obj The object to format.
189 * @param appendTo Output parameter to receive result.
190 * Result is appended to existing contents.
191 * @param pos On input: an alignment field, if desired.
192 * On output: the offsets of the alignment field.
193 * @param status Output param filled with success/failure status.
194 * @return Reference to 'appendTo' parameter.
197 virtual UnicodeString
& format(const Formattable
& obj
,
198 UnicodeString
& appendTo
,
200 UErrorCode
& status
) const;
203 * Parse a string to produce an object. This methods handles
204 * parsing of numeric strings into Formattable objects with numeric
207 * Before calling, set parse_pos.index to the offset you want to
208 * start parsing at in the source. After calling, parse_pos.index
209 * indicates the position after the successfully parsed text. If
210 * an error occurs, parse_pos.index is unchanged.
212 * When parsing, leading whitespace is discarded (with successful
213 * parse), while trailing whitespace is left as is.
215 * See Format::parseObject() for more.
217 * @param source The string to be parsed into an object.
218 * @param result Formattable to be set to the parse result.
219 * If parse fails, return contents are undefined.
220 * @param parse_pos The position to start parsing at. Upon return
221 * this param is set to the position after the
222 * last character successfully parsed. If the
223 * source is not parsed successfully, this param
224 * will remain unchanged.
225 * @return A newly created Formattable* object, or NULL
226 * on failure. The caller owns this and should
227 * delete it when done.
230 virtual void parseObject(const UnicodeString
& source
,
232 ParsePosition
& parse_pos
) const;
235 * Format a double number. These methods call the NumberFormat
236 * pure virtual format() methods with the default FieldPosition.
238 * @param number The value to be formatted.
239 * @param appendTo Output parameter to receive result.
240 * Result is appended to existing contents.
241 * @return Reference to 'appendTo' parameter.
244 UnicodeString
& format( double number
,
245 UnicodeString
& appendTo
) const;
248 * Format a long number. These methods call the NumberFormat
249 * pure virtual format() methods with the default FieldPosition.
251 * @param number The value to be formatted.
252 * @param appendTo Output parameter to receive result.
253 * Result is appended to existing contents.
254 * @return Reference to 'appendTo' parameter.
257 UnicodeString
& format( int32_t number
,
258 UnicodeString
& appendTo
) const;
261 * Format an int64 number. These methods call the NumberFormat
262 * pure virtual format() methods with the default FieldPosition.
264 * @param number The value to be formatted.
265 * @param appendTo Output parameter to receive result.
266 * Result is appended to existing contents.
267 * @return Reference to 'appendTo' parameter.
270 UnicodeString
& format( int64_t number
,
271 UnicodeString
& appendTo
) const;
274 * Format a double number. Concrete subclasses must implement
275 * these pure virtual methods.
277 * @param number The value to be formatted.
278 * @param appendTo Output parameter to receive result.
279 * Result is appended to existing contents.
280 * @param pos On input: an alignment field, if desired.
281 * On output: the offsets of the alignment field.
282 * @return Reference to 'appendTo' parameter.
285 virtual UnicodeString
& format(double number
,
286 UnicodeString
& appendTo
,
287 FieldPosition
& pos
) const = 0;
289 * Format a long number. Concrete subclasses must implement
290 * these pure virtual methods.
292 * @param number The value to be formatted.
293 * @param appendTo Output parameter to receive result.
294 * Result is appended to existing contents.
295 * @param pos On input: an alignment field, if desired.
296 * On output: the offsets of the alignment field.
297 * @return Reference to 'appendTo' parameter.
300 virtual UnicodeString
& format(int32_t number
,
301 UnicodeString
& appendTo
,
302 FieldPosition
& pos
) const = 0;
305 * Format an int64 number. (Not abstract to retain compatibility
306 * with earlier releases, however subclasses should override this
307 * method as it just delegates to format(int32_t number...);
309 * @param number The value to be formatted.
310 * @param appendTo Output parameter to receive result.
311 * Result is appended to existing contents.
312 * @param pos On input: an alignment field, if desired.
313 * On output: the offsets of the alignment field.
314 * @return Reference to 'appendTo' parameter.
317 virtual UnicodeString
& format(int64_t number
,
318 UnicodeString
& appendTo
,
319 FieldPosition
& pos
) const;
321 * Redeclared Format method.
322 * @param obj The object to be formatted.
323 * @param appendTo Output parameter to receive result.
324 * Result is appended to existing contents.
325 * @param status Output parameter set to a failure error code
326 * when a failure occurs.
327 * @return Reference to 'appendTo' parameter.
330 UnicodeString
& format(const Formattable
& obj
,
331 UnicodeString
& appendTo
,
332 UErrorCode
& status
) const;
335 * Return a long if possible (e.g. within range LONG_MAX,
336 * LONG_MAX], and with no decimals), otherwise a double. If
337 * IntegerOnly is set, will stop at a decimal point (or equivalent;
338 * e.g. for rational numbers "1 2/3", will stop after the 1).
340 * If no object can be parsed, index is unchanged, and NULL is
343 * This is a pure virtual which concrete subclasses must implement.
345 * @param text The text to be parsed.
346 * @param result Formattable to be set to the parse result.
347 * If parse fails, return contents are undefined.
348 * @param parsePosition The position to start parsing at on input.
349 * On output, moved to after the last successfully
350 * parse character. On parse failure, does not change.
351 * @return A Formattable object of numeric type. The caller
352 * owns this an must delete it. NULL on failure.
355 virtual void parse(const UnicodeString
& text
,
357 ParsePosition
& parsePosition
) const = 0;
360 * Parse a string as a numeric value, and return a Formattable
361 * numeric object. This method parses integers only if IntegerOnly
364 * @param text The text to be parsed.
365 * @param result Formattable to be set to the parse result.
366 * If parse fails, return contents are undefined.
367 * @param status Output parameter set to a failure error code
368 * when a failure occurs.
369 * @return A Formattable object of numeric type. The caller
370 * owns this an must delete it. NULL on failure.
371 * @see NumberFormat::isParseIntegerOnly
374 virtual void parse( const UnicodeString
& text
,
376 UErrorCode
& status
) const;
379 * Parses text from the given string as a currency amount. Unlike
380 * the parse() method, this method will attempt to parse a generic
381 * currency name, searching for a match of this object's locale's
382 * currency display names, or for a 3-letter ISO currency code.
383 * This method will fail if this format is not a currency format,
384 * that is, if it does not contain the currency pattern symbol
385 * (U+00A4) in its prefix or suffix.
387 * @param text the string to parse
388 * @param result output parameter to receive result. This will have
389 * its currency set to the parsed ISO currency code.
390 * @param pos input-output position; on input, the position within
391 * text to match; must have 0 <= pos.getIndex() < text.length();
392 * on output, the position after the last matched character. If
393 * the parse fails, the position in unchanged upon output.
394 * @return a reference to result
397 virtual Formattable
& parseCurrency(const UnicodeString
& text
,
399 ParsePosition
& pos
) const;
402 * Return true if this format will parse numbers as integers
403 * only. For example in the English locale, with ParseIntegerOnly
404 * true, the string "1234." would be parsed as the integer value
405 * 1234 and parsing would stop at the "." character. Of course,
406 * the exact format accepted by the parse operation is locale
407 * dependant and determined by sub-classes of NumberFormat.
408 * @return true if this format will parse numbers as integers
412 UBool
isParseIntegerOnly(void) const;
415 * Sets whether or not numbers should be parsed as integers only.
416 * @param value set True, this format will parse numbers as integers
418 * @see isParseIntegerOnly
421 virtual void setParseIntegerOnly(UBool value
);
424 * Returns the default number format for the current default
425 * locale. The default format is one of the styles provided by
426 * the other factory methods: getNumberInstance,
427 * getCurrencyInstance or getPercentInstance. Exactly which one
428 * is locale dependant.
431 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
434 * Returns the default number format for the specified locale.
435 * The default format is one of the styles provided by the other
436 * factory methods: getNumberInstance, getCurrencyInstance or
437 * getPercentInstance. Exactly which one is locale dependant.
438 * @param inLocale the given locale.
441 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& inLocale
,
445 * Returns a currency format for the current default locale.
448 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
451 * Returns a currency format for the specified locale.
452 * @param inLocale the given locale.
455 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
459 * Returns a percentage format for the current default locale.
462 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
465 * Returns a percentage format for the specified locale.
466 * @param inLocale the given locale.
469 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
473 * Returns a scientific format for the current default locale.
476 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
479 * Returns a scientific format for the specified locale.
480 * @param inLocale the given locale.
483 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
487 * Get the set of Locales for which NumberFormats are installed.
488 * @param count Output param to receive the size of the locales
491 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
493 #if !UCONFIG_NO_SERVICE
495 * Register a new NumberFormatFactory. The factory will be adopted.
496 * @param toAdopt the NumberFormatFactory instance to be adopted
497 * @param status the in/out status code, no special meanings are assigned
498 * @return a registry key that can be used to unregister this factory
501 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
504 * Unregister a previously-registered NumberFormatFactory using the key returned from the
505 * register call. Key becomes invalid after a successful call and should not be used again.
506 * The NumberFormatFactory corresponding to the key will be deleted.
507 * @param key the registry key returned by a previous call to registerFactory
508 * @param status the in/out status code, no special meanings are assigned
509 * @return TRUE if the factory for the key was successfully unregistered
512 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
515 * Return a StringEnumeration over the locales available at the time of the call,
516 * including registered locales.
517 * @return a StringEnumeration over the locales available at the time of the call
520 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
521 #endif /* UCONFIG_NO_SERVICE */
524 * Returns true if grouping is used in this format. For example,
525 * in the English locale, with grouping on, the number 1234567
526 * might be formatted as "1,234,567". The grouping separator as
527 * well as the size of each group is locale dependant and is
528 * determined by sub-classes of NumberFormat.
529 * @see setGroupingUsed
532 UBool
isGroupingUsed(void) const;
535 * Set whether or not grouping will be used in this format.
536 * @param newValue True, grouping will be used in this format.
537 * @see getGroupingUsed
540 virtual void setGroupingUsed(UBool newValue
);
543 * Returns the maximum number of digits allowed in the integer portion of a
545 * @return the maximum number of digits allowed in the integer portion of a
547 * @see setMaximumIntegerDigits
550 int32_t getMaximumIntegerDigits(void) const;
553 * Sets the maximum number of digits allowed in the integer portion of a
554 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
555 * new value for maximumIntegerDigits is less than the current value
556 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
559 * @param newValue the new value for the maximum number of digits
560 * allowed in the integer portion of a number.
561 * @see getMaximumIntegerDigits
564 virtual void setMaximumIntegerDigits(int32_t newValue
);
567 * Returns the minimum number of digits allowed in the integer portion of a
569 * @return the minimum number of digits allowed in the integer portion of a
571 * @see setMinimumIntegerDigits
574 int32_t getMinimumIntegerDigits(void) const;
577 * Sets the minimum number of digits allowed in the integer portion of a
578 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
579 * new value for minimumIntegerDigits exceeds the current value
580 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
582 * @param newValue the new value to be set.
583 * @see getMinimumIntegerDigits
586 virtual void setMinimumIntegerDigits(int32_t newValue
);
589 * Returns the maximum number of digits allowed in the fraction portion of a
591 * @return the maximum number of digits allowed in the fraction portion of a
593 * @see setMaximumFractionDigits
596 int32_t getMaximumFractionDigits(void) const;
599 * Sets the maximum number of digits allowed in the fraction portion of a
600 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
601 * new value for maximumFractionDigits is less than the current value
602 * of minimumFractionDigits, then minimumFractionDigits will also be set to
604 * @param newValue the new value to be set.
605 * @see getMaximumFractionDigits
608 virtual void setMaximumFractionDigits(int32_t newValue
);
611 * Returns the minimum number of digits allowed in the fraction portion of a
613 * @return the minimum number of digits allowed in the fraction portion of a
615 * @see setMinimumFractionDigits
618 int32_t getMinimumFractionDigits(void) const;
621 * Sets the minimum number of digits allowed in the fraction portion of a
622 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
623 * new value for minimumFractionDigits exceeds the current value
624 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
626 * @param newValue the new value to be set.
627 * @see getMinimumFractionDigits
630 virtual void setMinimumFractionDigits(int32_t newValue
);
633 * Sets the currency used to display currency
634 * amounts. This takes effect immediately, if this format is a
635 * currency format. If this format is not a currency format, then
636 * the currency is used if and when this object becomes a
638 * @param theCurrency a 3-letter ISO code indicating new currency
639 * to use. It need not be null-terminated. May be the empty
640 * string or NULL to indicate no currency.
641 * @param ec input-output error code
644 virtual void setCurrency(const UChar
* theCurrency
, UErrorCode
& ec
);
647 * Gets the currency used to display currency
648 * amounts. This may be an empty string for some subclasses.
649 * @return a 3-letter null-terminated ISO code indicating
650 * the currency in use, or a pointer to the empty string.
653 const UChar
* getCurrency() const;
658 * Return the class ID for this class. This is useful for
659 * comparing to a return value from getDynamicClassID(). Note that,
660 * because NumberFormat is an abstract base class, no fully constructed object
661 * will have the class ID returned by NumberFormat::getStaticClassID().
662 * @return The class ID for all objects of this class.
665 static UClassID U_EXPORT2
getStaticClassID(void);
668 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
669 * This method is to implement a simple version of RTTI, since not all
670 * C++ compilers support genuine RTTI. Polymorphic operator==() and
671 * clone() methods call this method.
673 * @return The class ID for this object. All objects of a
674 * given class have the same class ID. Objects of
675 * other classes have different class IDs.
678 virtual UClassID
getDynamicClassID(void) const = 0;
683 * Default constructor for subclass use only.
692 NumberFormat(const NumberFormat
&);
695 * Assignment operator.
698 NumberFormat
& operator=(const NumberFormat
&);
701 * Returns the currency in effect for this formatter. Subclasses
702 * should override this method as needed. Unlike getCurrency(),
703 * this method should never return "".
704 * @result output parameter for null-terminated result, which must
705 * have a capacity of at least 4
708 virtual void getEffectiveCurrency(UChar
* result
, UErrorCode
& ec
) const;
711 static const int32_t fgMaxIntegerDigits
;
712 static const int32_t fgMinIntegerDigits
;
721 kStyleCount
// ALWAYS LAST ENUM: number of styles
725 * Creates the specified decimal format style of the desired locale.
726 * Hook for service registration, uses makeInstance directly if no services
728 * @param desiredLocale the given locale.
729 * @param choice the given style.
730 * @param success Output param filled with success/failure status.
731 * @return A new NumberFormat instance.
733 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
736 * Creates the specified decimal format style of the desired locale.
737 * @param desiredLocale the given locale.
738 * @param choice the given style.
739 * @param success Output param filled with success/failure status.
740 * @return A new NumberFormat instance.
742 static NumberFormat
* makeInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
743 static const int32_t fgNumberPatternsCount
;
744 static const UChar
* const fgLastResortNumberPatterns
[];
747 int32_t fMaxIntegerDigits
;
748 int32_t fMinIntegerDigits
;
749 int32_t fMaxFractionDigits
;
750 int32_t fMinFractionDigits
;
751 UBool fParseIntegerOnly
;
756 friend class ICUNumberFormatFactory
; // access to makeInstance, EStyles
757 friend class ICUNumberFormatService
;
760 #if !UCONFIG_NO_SERVICE
762 * A NumberFormatFactory is used to register new number formats. The factory
763 * should be able to create any of the predefined formats for each locale it
764 * supports. When registered, the locales it supports extend or override the
765 * locale already supported by ICU.
769 class U_I18N_API NumberFormatFactory
: public UObject
{
776 virtual ~NumberFormatFactory();
779 * Return true if this factory will be visible. Default is true.
780 * If not visible, the locales supported by this factory will not
781 * be listed by getAvailableLocales.
784 virtual UBool
visible(void) const = 0;
787 * Return the locale names directly supported by this factory. The number of names
788 * is returned in count;
791 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
794 * Return a number format of the appropriate type. If the locale
795 * is not supported, return null. If the locale is supported, but
796 * the type is not provided by this service, return null. Otherwise
797 * return an appropriate instance of NumberFormat.
800 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
804 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
807 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
810 * True if the locale supported by this factory is visible.
813 const UBool _visible
;
816 * The locale supported by this factory, as a UnicodeString.
825 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
830 virtual ~SimpleNumberFormatFactory();
835 virtual UBool
visible(void) const;
840 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
842 #endif /* #if !UCONFIG_NO_SERVICE */
844 // -------------------------------------
847 NumberFormat::isParseIntegerOnly() const
849 return fParseIntegerOnly
;
852 inline UnicodeString
&
853 NumberFormat::format(const Formattable
& obj
,
854 UnicodeString
& appendTo
,
855 UErrorCode
& status
) const {
856 return Format::format(obj
, appendTo
, status
);
861 #endif /* #if !UCONFIG_NO_FORMATTING */