2 ********************************************************************************
3 * Copyright (C) 1997-2006, 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 * Returns the default number format for the current default
428 * locale. The default format is one of the styles provided by
429 * the other factory methods: getNumberInstance,
430 * getCurrencyInstance or getPercentInstance. Exactly which one
431 * is locale dependant.
434 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
437 * Returns the default number format for the specified locale.
438 * The default format is one of the styles provided by the other
439 * factory methods: getNumberInstance, getCurrencyInstance or
440 * getPercentInstance. Exactly which one is locale dependant.
441 * @param inLocale the given locale.
444 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& inLocale
,
448 * Returns a currency format for the current default locale.
451 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
454 * Returns a currency format for the specified locale.
455 * @param inLocale the given locale.
458 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
462 * Returns a percentage format for the current default locale.
465 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
468 * Returns a percentage format for the specified locale.
469 * @param inLocale the given locale.
472 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
476 * Returns a scientific format for the current default locale.
479 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
482 * Returns a scientific format for the specified locale.
483 * @param inLocale the given locale.
486 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
490 * Get the set of Locales for which NumberFormats are installed.
491 * @param count Output param to receive the size of the locales
494 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
496 #if !UCONFIG_NO_SERVICE
498 * Register a new NumberFormatFactory. The factory will be adopted.
499 * @param toAdopt the NumberFormatFactory instance to be adopted
500 * @param status the in/out status code, no special meanings are assigned
501 * @return a registry key that can be used to unregister this factory
504 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
507 * Unregister a previously-registered NumberFormatFactory using the key returned from the
508 * register call. Key becomes invalid after a successful call and should not be used again.
509 * The NumberFormatFactory corresponding to the key will be deleted.
510 * @param key the registry key returned by a previous call to registerFactory
511 * @param status the in/out status code, no special meanings are assigned
512 * @return TRUE if the factory for the key was successfully unregistered
515 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
518 * Return a StringEnumeration over the locales available at the time of the call,
519 * including registered locales.
520 * @return a StringEnumeration over the locales available at the time of the call
523 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
524 #endif /* UCONFIG_NO_SERVICE */
527 * Returns true if grouping is used in this format. For example,
528 * in the English locale, with grouping on, the number 1234567
529 * might be formatted as "1,234,567". The grouping separator as
530 * well as the size of each group is locale dependant and is
531 * determined by sub-classes of NumberFormat.
532 * @see setGroupingUsed
535 UBool
isGroupingUsed(void) const;
538 * Set whether or not grouping will be used in this format.
539 * @param newValue True, grouping will be used in this format.
540 * @see getGroupingUsed
543 virtual void setGroupingUsed(UBool newValue
);
546 * Returns the maximum number of digits allowed in the integer portion of a
548 * @return the maximum number of digits allowed in the integer portion of a
550 * @see setMaximumIntegerDigits
553 int32_t getMaximumIntegerDigits(void) const;
556 * Sets the maximum number of digits allowed in the integer portion of a
557 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
558 * new value for maximumIntegerDigits is less than the current value
559 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
562 * @param newValue the new value for the maximum number of digits
563 * allowed in the integer portion of a number.
564 * @see getMaximumIntegerDigits
567 virtual void setMaximumIntegerDigits(int32_t newValue
);
570 * Returns the minimum number of digits allowed in the integer portion of a
572 * @return the minimum number of digits allowed in the integer portion of a
574 * @see setMinimumIntegerDigits
577 int32_t getMinimumIntegerDigits(void) const;
580 * Sets the minimum number of digits allowed in the integer portion of a
581 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
582 * new value for minimumIntegerDigits exceeds the current value
583 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
585 * @param newValue the new value to be set.
586 * @see getMinimumIntegerDigits
589 virtual void setMinimumIntegerDigits(int32_t newValue
);
592 * Returns the maximum number of digits allowed in the fraction portion of a
594 * @return the maximum number of digits allowed in the fraction portion of a
596 * @see setMaximumFractionDigits
599 int32_t getMaximumFractionDigits(void) const;
602 * Sets the maximum number of digits allowed in the fraction portion of a
603 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
604 * new value for maximumFractionDigits is less than the current value
605 * of minimumFractionDigits, then minimumFractionDigits will also be set to
607 * @param newValue the new value to be set.
608 * @see getMaximumFractionDigits
611 virtual void setMaximumFractionDigits(int32_t newValue
);
614 * Returns the minimum number of digits allowed in the fraction portion of a
616 * @return the minimum number of digits allowed in the fraction portion of a
618 * @see setMinimumFractionDigits
621 int32_t getMinimumFractionDigits(void) const;
624 * Sets the minimum number of digits allowed in the fraction portion of a
625 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
626 * new value for minimumFractionDigits exceeds the current value
627 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
629 * @param newValue the new value to be set.
630 * @see getMinimumFractionDigits
633 virtual void setMinimumFractionDigits(int32_t newValue
);
636 * Sets the currency used to display currency
637 * amounts. This takes effect immediately, if this format is a
638 * currency format. If this format is not a currency format, then
639 * the currency is used if and when this object becomes a
641 * @param theCurrency a 3-letter ISO code indicating new currency
642 * to use. It need not be null-terminated. May be the empty
643 * string or NULL to indicate no currency.
644 * @param ec input-output error code
647 virtual void setCurrency(const UChar
* theCurrency
, UErrorCode
& ec
);
650 * Gets the currency used to display currency
651 * amounts. This may be an empty string for some subclasses.
652 * @return a 3-letter null-terminated ISO code indicating
653 * the currency in use, or a pointer to the empty string.
656 const UChar
* getCurrency() const;
661 * Return the class ID for this class. This is useful for
662 * comparing to a return value from getDynamicClassID(). Note that,
663 * because NumberFormat is an abstract base class, no fully constructed object
664 * will have the class ID returned by NumberFormat::getStaticClassID().
665 * @return The class ID for all objects of this class.
668 static UClassID U_EXPORT2
getStaticClassID(void);
671 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
672 * This method is to implement a simple version of RTTI, since not all
673 * C++ compilers support genuine RTTI. Polymorphic operator==() and
674 * clone() methods call this method.
676 * @return The class ID for this object. All objects of a
677 * given class have the same class ID. Objects of
678 * other classes have different class IDs.
681 virtual UClassID
getDynamicClassID(void) const = 0;
686 * Default constructor for subclass use only.
695 NumberFormat(const NumberFormat
&);
698 * Assignment operator.
701 NumberFormat
& operator=(const NumberFormat
&);
704 * Returns the currency in effect for this formatter. Subclasses
705 * should override this method as needed. Unlike getCurrency(),
706 * this method should never return "".
707 * @result output parameter for null-terminated result, which must
708 * have a capacity of at least 4
711 virtual void getEffectiveCurrency(UChar
* result
, UErrorCode
& ec
) const;
720 kStyleCount
// ALWAYS LAST ENUM: number of styles
724 * Creates the specified decimal format style of the desired locale.
725 * Hook for service registration, uses makeInstance directly if no services
727 * @param desiredLocale the given locale.
728 * @param choice the given style.
729 * @param success Output param filled with success/failure status.
730 * @return A new NumberFormat instance.
732 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
735 * Creates the specified decimal format style of the desired locale.
736 * @param desiredLocale the given locale.
737 * @param choice the given style.
738 * @param success Output param filled with success/failure status.
739 * @return A new NumberFormat instance.
741 static NumberFormat
* makeInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
744 int32_t fMaxIntegerDigits
;
745 int32_t fMinIntegerDigits
;
746 int32_t fMaxFractionDigits
;
747 int32_t fMinFractionDigits
;
748 UBool fParseIntegerOnly
;
753 friend class ICUNumberFormatFactory
; // access to makeInstance, EStyles
754 friend class ICUNumberFormatService
;
757 #if !UCONFIG_NO_SERVICE
759 * A NumberFormatFactory is used to register new number formats. The factory
760 * should be able to create any of the predefined formats for each locale it
761 * supports. When registered, the locales it supports extend or override the
762 * locale already supported by ICU.
766 class U_I18N_API NumberFormatFactory
: public UObject
{
773 virtual ~NumberFormatFactory();
776 * Return true if this factory will be visible. Default is true.
777 * If not visible, the locales supported by this factory will not
778 * be listed by getAvailableLocales.
781 virtual UBool
visible(void) const = 0;
784 * Return the locale names directly supported by this factory. The number of names
785 * is returned in count;
788 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
791 * Return a number format of the appropriate type. If the locale
792 * is not supported, return null. If the locale is supported, but
793 * the type is not provided by this service, return null. Otherwise
794 * return an appropriate instance of NumberFormat.
797 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
801 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
804 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
807 * True if the locale supported by this factory is visible.
810 const UBool _visible
;
813 * The locale supported by this factory, as a UnicodeString.
822 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
827 virtual ~SimpleNumberFormatFactory();
832 virtual UBool
visible(void) const;
837 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
839 #endif /* #if !UCONFIG_NO_SERVICE */
841 // -------------------------------------
844 NumberFormat::isParseIntegerOnly() const
846 return fParseIntegerOnly
;
849 inline UnicodeString
&
850 NumberFormat::format(const Formattable
& obj
,
851 UnicodeString
& appendTo
,
852 UErrorCode
& status
) const {
853 return Format::format(obj
, appendTo
, status
);
858 #endif /* #if !UCONFIG_NO_FORMATTING */