2 * Copyright (C) {1997-2003}, 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 class NumberFormatFactory
;
35 class StringEnumeration
;
37 typedef const void* URegistryKey
;
40 * Abstract base class for all number formats. Provides interface for
41 * formatting and parsing a number. Also provides methods for
42 * determining which locales have number formats, and what their names
45 * NumberFormat helps you to format and parse numbers for any locale.
46 * Your code can be completely independent of the locale conventions
47 * for decimal points, thousands-separators, or even the particular
48 * decimal digits used, or whether the number format is even decimal.
50 * To format a number for the current Locale, use one of the static
54 * double myNumber = 7.0;
55 * UnicodeString myString;
56 * UErrorCode success = U_ZERO_ERROR;
57 * NumberFormat* nf = NumberFormat::createInstance(success)
58 * nf->format(myNumber, myString);
59 * cout << " Example 1: " << myString << endl;
62 * If you are formatting multiple numbers, it is more efficient to get
63 * the format and use it multiple times so that the system doesn't
64 * have to fetch the information about the local language and country
65 * conventions multiple times.
68 * UnicodeString myString;
69 * UErrorCode success = U_ZERO_ERROR;
70 * nf = NumberFormat::createInstance( success );
71 * int32_t a[] = { 123, 3333, -1234567 };
72 * const int32_t a_len = sizeof(a) / sizeof(a[0]);
74 * for (int32_t i = 0; i < a_len; i++) {
75 * nf->format(a[i], myString);
78 * cout << " Example 2: " << myString << endl;
81 * To format a number for a different Locale, specify it in the
82 * call to createInstance().
85 * nf = NumberFormat::createInstance( Locale::FRENCH, success );
88 * You can use a NumberFormat to parse also.
92 * Formattable result(-999); // initialized with error code
93 * nf->parse(myString, result, success);
96 * Use createInstance to get the normal number format for that country.
97 * There are other static factory methods available. Use getCurrency
98 * to get the currency number format for that country. Use getPercent
99 * to get a format for displaying percentages. With this format, a
100 * fraction from 0.53 is displayed as 53%.
102 * You can also control the display of numbers with such methods as
103 * getMinimumFractionDigits. If you want even more control over the
104 * format or parsing, or want to give your users more control, you can
105 * try casting the NumberFormat you get from the factory methods to a
106 * DecimalNumberFormat. This will work for the vast majority of
107 * countries; just remember to put it in a try block in case you
108 * encounter an unusual one.
110 * You can also use forms of the parse and format methods with
111 * ParsePosition and FieldPosition to allow you to:
113 * <li>(a) progressively parse through pieces of a string.
114 * <li>(b) align the decimal point and other areas.
116 * For example, you can align numbers in two ways.
118 * If you are using a monospaced font with spacing for alignment, you
119 * can pass the FieldPosition in your format call, with field =
120 * INTEGER_FIELD. On output, getEndIndex will be set to the offset
121 * between the last character of the integer and the decimal. Add
122 * (desiredSpaceCount - getEndIndex) spaces at the front of the
125 * If you are using proportional fonts, instead of padding with
126 * spaces, measure the width of the string in pixels from the start to
127 * getEndIndex. Then move the pen by (desiredPixelWidth -
128 * widthToAlignmentPoint) before drawing the text. It also works
129 * where there is no decimal, but possibly additional characters at
130 * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
133 class U_I18N_API NumberFormat
: public Format
{
137 * Alignment Field constants used to construct a FieldPosition object.
138 * Signifies that the position of the integer part or fraction part of
139 * a formatted number should be returned.
144 enum EAlignmentFields
{
150 * These constants are provided for backwards compatibility only.
151 * Please use the C++ style constants defined above.
154 INTEGER_FIELD
= kIntegerField
,
155 FRACTION_FIELD
= kFractionField
162 virtual ~NumberFormat();
165 * Return true if the given Format objects are semantically equal.
166 * Objects of different subclasses are considered unequal.
167 * @return true if the given Format objects are semantically equal.
170 virtual UBool
operator==(const Format
& other
) const;
173 * Format an object to produce a string. This method handles
174 * Formattable objects with numeric types. If the Formattable
175 * object type is not a numeric type, then it returns a failing
178 * @param obj The object to format.
179 * @param appendTo Output parameter to receive result.
180 * Result is appended to existing contents.
181 * @param pos On input: an alignment field, if desired.
182 * On output: the offsets of the alignment field.
183 * @param status Output param filled with success/failure status.
184 * @return Reference to 'appendTo' parameter.
187 virtual UnicodeString
& format(const Formattable
& obj
,
188 UnicodeString
& appendTo
,
190 UErrorCode
& status
) const;
193 * Parse a string to produce an object. This methods handles
194 * parsing of numeric strings into Formattable objects with numeric
197 * Before calling, set parse_pos.index to the offset you want to
198 * start parsing at in the source. After calling, parse_pos.index
199 * is the end of the text you parsed. If error occurs, index is
202 * When parsing, leading whitespace is discarded (with successful
203 * parse), while trailing whitespace is left as is.
205 * See Format::parseObject() for more.
207 * @param source The string to be parsed into an object.
208 * @param result Formattable to be set to the parse result.
209 * If parse fails, return contents are undefined.
210 * @param parse_pos The position to start parsing at. Upon return
211 * this param is set to the position after the
212 * last character successfully parsed. If the
213 * source is not parsed successfully, this param
214 * will remain unchanged.
215 * @return A newly created Formattable* object, or NULL
216 * on failure. The caller owns this and should
217 * delete it when done.
220 virtual void parseObject(const UnicodeString
& source
,
222 ParsePosition
& parse_pos
) const;
225 * Format a double number. These methods call the NumberFormat
226 * pure virtual format() methods with the default FieldPosition.
228 * @param number The value to be formatted.
229 * @param appendTo Output parameter to receive result.
230 * Result is appended to existing contents.
231 * @return Reference to 'appendTo' parameter.
234 UnicodeString
& format( double number
,
235 UnicodeString
& appendTo
) const;
238 * Format a long 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( int32_t number
,
248 UnicodeString
& appendTo
) const;
251 * Format a double number. Concrete subclasses must implement
252 * these pure virtual methods.
254 * @param number The value to be formatted.
255 * @param appendTo Output parameter to receive result.
256 * Result is appended to existing contents.
257 * @param pos On input: an alignment field, if desired.
258 * On output: the offsets of the alignment field.
259 * @return Reference to 'appendTo' parameter.
262 virtual UnicodeString
& format(double number
,
263 UnicodeString
& appendTo
,
264 FieldPosition
& pos
) const = 0;
266 * Format a long number. Concrete subclasses must implement
267 * these pure virtual methods.
269 * @param number The value to be formatted.
270 * @param appendTo Output parameter to receive result.
271 * Result is appended to existing contents.
272 * @param pos On input: an alignment field, if desired.
273 * On output: the offsets of the alignment field.
274 * @return Reference to 'appendTo' parameter.
277 virtual UnicodeString
& format(int32_t number
,
278 UnicodeString
& appendTo
,
279 FieldPosition
& pos
) const = 0;
282 * Redeclared Format method.
283 * @param obj The object to be formatted.
284 * @param appendTo Output parameter to receive result.
285 * Result is appended to existing contents.
286 * @param status Output parameter set to a failure error code
287 * when a failure occurs.
288 * @return Reference to 'appendTo' parameter.
291 UnicodeString
& format(const Formattable
& obj
,
292 UnicodeString
& appendTo
,
293 UErrorCode
& status
) const;
296 * Return a long if possible (e.g. within range LONG_MAX,
297 * LONG_MAX], and with no decimals), otherwise a double. If
298 * IntegerOnly is set, will stop at a decimal point (or equivalent;
299 * e.g. for rational numbers "1 2/3", will stop after the 1).
301 * If no object can be parsed, index is unchanged, and NULL is
304 * This is a pure virtual which concrete subclasses must implement.
306 * @param text The text to be parsed.
307 * @param result Formattable to be set to the parse result.
308 * If parse fails, return contents are undefined.
309 * @param parsePosition The position to start parsing at on input.
310 * On output, moved to after the last successfully
311 * parse character. On parse failure, does not change.
312 * @return A Formattable object of numeric type. The caller
313 * owns this an must delete it. NULL on failure.
316 virtual void parse(const UnicodeString
& text
,
318 ParsePosition
& parsePosition
) const = 0;
321 * Parse a string as a numeric value, and return a Formattable
322 * numeric object. This method parses integers only if IntegerOnly
325 * @param text The text to be parsed.
326 * @param result Formattable to be set to the parse result.
327 * If parse fails, return contents are undefined.
328 * @param status Output parameter set to a failure error code
329 * when a failure occurs.
330 * @return A Formattable object of numeric type. The caller
331 * owns this an must delete it. NULL on failure.
332 * @see NumberFormat::isParseIntegerOnly
335 virtual void parse( const UnicodeString
& text
,
337 UErrorCode
& status
) const;
340 * Return true if this format will parse numbers as integers
341 * only. For example in the English locale, with ParseIntegerOnly
342 * true, the string "1234." would be parsed as the integer value
343 * 1234 and parsing would stop at the "." character. Of course,
344 * the exact format accepted by the parse operation is locale
345 * dependant and determined by sub-classes of NumberFormat.
346 * @return true if this format will parse numbers as integers
350 UBool
isParseIntegerOnly(void) const;
353 * Sets whether or not numbers should be parsed as integers only.
354 * @param value set True, this format will parse numbers as integers
356 * @see isParseIntegerOnly
359 virtual void setParseIntegerOnly(UBool value
);
362 * Returns the default number format for the current default
363 * locale. The default format is one of the styles provided by
364 * the other factory methods: getNumberInstance,
365 * getCurrencyInstance or getPercentInstance. Exactly which one
366 * is locale dependant.
369 static NumberFormat
* createInstance(UErrorCode
&);
372 * Returns the default number format for the specified locale.
373 * The default format is one of the styles provided by the other
374 * factory methods: getNumberInstance, getCurrencyInstance or
375 * getPercentInstance. Exactly which one is locale dependant.
376 * @param inLocale the given locale.
379 static NumberFormat
* createInstance(const Locale
& inLocale
,
383 * Returns a currency format for the current default locale.
386 static NumberFormat
* createCurrencyInstance(UErrorCode
&);
389 * Returns a currency format for the specified locale.
390 * @param inLocale the given locale.
393 static NumberFormat
* createCurrencyInstance(const Locale
& inLocale
,
397 * Returns a percentage format for the current default locale.
400 static NumberFormat
* createPercentInstance(UErrorCode
&);
403 * Returns a percentage format for the specified locale.
404 * @param inLocale the given locale.
407 static NumberFormat
* createPercentInstance(const Locale
& inLocale
,
411 * Returns a scientific format for the current default locale.
414 static NumberFormat
* createScientificInstance(UErrorCode
&);
417 * Returns a scientific format for the specified locale.
418 * @param inLocale the given locale.
421 static NumberFormat
* createScientificInstance(const Locale
& inLocale
,
425 * Get the set of Locales for which NumberFormats are installed.
426 * @param count Output param to receive the size of the locales
429 static const Locale
* getAvailableLocales(int32_t& count
);
432 * Register a new NumberFormatFactory. The factory will be adopted.
433 * @param toAdopt the NumberFormatFactory instance to be adopted
434 * @param status the in/out status code, no special meanings are assigned
435 * @return a registry key that can be used to unregister this factory
438 static URegistryKey
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
441 * Unregister a previously-registered NumberFormatFactory using the key returned from the
442 * register call. Key becomes invalid after a successful call and should not be used again.
443 * The NumberFormatFactory corresponding to the key will be deleted.
444 * @param key the registry key returned by a previous call to registerFactory
445 * @param status the in/out status code, no special meanings are assigned
446 * @return TRUE if the factory for the key was successfully unregistered
449 static UBool
unregister(URegistryKey key
, UErrorCode
& status
);
452 * Return a StringEnumeration over the locales available at the time of the call,
453 * including registered locales.
454 * @return a StringEnumeration over the locales available at the time of the call
457 static StringEnumeration
* getAvailableLocales(void);
460 * Returns true if grouping is used in this format. For example,
461 * in the English locale, with grouping on, the number 1234567
462 * might be formatted as "1,234,567". The grouping separator as
463 * well as the size of each group is locale dependant and is
464 * determined by sub-classes of NumberFormat.
465 * @see setGroupingUsed
468 UBool
isGroupingUsed(void) const;
471 * Set whether or not grouping will be used in this format.
472 * @param newValue True, grouping will be used in this format.
473 * @see getGroupingUsed
476 virtual void setGroupingUsed(UBool newValue
);
479 * Returns the maximum number of digits allowed in the integer portion of a
481 * @return the maximum number of digits allowed in the integer portion of a
483 * @see setMaximumIntegerDigits
486 int32_t getMaximumIntegerDigits(void) const;
489 * Sets the maximum number of digits allowed in the integer portion of a
490 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
491 * new value for maximumIntegerDigits is less than the current value
492 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
495 * @param newValue the new value for the maximum number of digits
496 * allowed in the integer portion of a number.
497 * @see getMaximumIntegerDigits
500 virtual void setMaximumIntegerDigits(int32_t newValue
);
503 * Returns the minimum number of digits allowed in the integer portion of a
505 * @return the minimum number of digits allowed in the integer portion of a
507 * @see setMinimumIntegerDigits
510 int32_t getMinimumIntegerDigits(void) const;
513 * Sets the minimum number of digits allowed in the integer portion of a
514 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
515 * new value for minimumIntegerDigits exceeds the current value
516 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
518 * @param newValue the new value to be set.
519 * @see getMinimumIntegerDigits
522 virtual void setMinimumIntegerDigits(int32_t newValue
);
525 * Returns the maximum number of digits allowed in the fraction portion of a
527 * @return the maximum number of digits allowed in the fraction portion of a
529 * @see setMaximumFractionDigits
532 int32_t getMaximumFractionDigits(void) const;
535 * Sets the maximum number of digits allowed in the fraction portion of a
536 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
537 * new value for maximumFractionDigits is less than the current value
538 * of minimumFractionDigits, then minimumFractionDigits will also be set to
540 * @param newValue the new value to be set.
541 * @see getMaximumFractionDigits
544 virtual void setMaximumFractionDigits(int32_t newValue
);
547 * Returns the minimum number of digits allowed in the fraction portion of a
549 * @return the minimum number of digits allowed in the fraction portion of a
551 * @see setMinimumFractionDigits
554 int32_t getMinimumFractionDigits(void) const;
557 * Sets the minimum number of digits allowed in the fraction portion of a
558 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
559 * new value for minimumFractionDigits exceeds the current value
560 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
562 * @param newValue the new value to be set.
563 * @see getMinimumFractionDigits
566 virtual void setMinimumFractionDigits(int32_t newValue
);
569 * Sets the currency used to display currency
570 * amounts. This takes effect immediately, if this format is a
571 * currency format. If this format is not a currency format, then
572 * the currency is used if and when this object becomes a
574 * @param theCurrency a 3-letter ISO code indicating new currency
575 * to use. It need not be null-terminated. May be the empty
576 * string or NULL to indicate no currency.
579 virtual void setCurrency(const UChar
* theCurrency
);
582 * Gets the currency used to display currency
583 * amounts. This may be an empty string for some subclasses.
584 * @return a 3-letter null-terminated ISO code indicating
585 * the currency in use, or a pointer to the empty string.
588 const UChar
* getCurrency() const;
593 * Return the class ID for this class. This is useful only for
594 * comparing to a return value from getDynamicClassID(). For example:
596 * . Base* polymorphic_pointer = createPolymorphicObject();
597 * . if (polymorphic_pointer->getDynamicClassID() ==
598 * . Derived::getStaticClassID()) ...
600 * @return The class ID for all objects of this class.
603 static inline UClassID
getStaticClassID(void);
606 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
607 * This method is to implement a simple version of RTTI, since not all
608 * C++ compilers support genuine RTTI. Polymorphic operator==() and
609 * clone() methods call this method.
611 * @return The class ID for this object. All objects of a
612 * given class have the same class ID. Objects of
613 * other classes have different class IDs.
616 virtual UClassID
getDynamicClassID(void) const = 0;
621 * Default constructor for subclass use only.
630 NumberFormat(const NumberFormat
&);
633 * Assignment operator.
636 NumberFormat
& operator=(const NumberFormat
&);
639 static const int32_t fgMaxIntegerDigits
;
640 static const int32_t fgMinIntegerDigits
;
643 static const char fgClassID
;
650 kStyleCount
// ALWAYS LAST ENUM: number of styles
654 * Creates the specified decimal format style of the desired locale.
655 * Hook for service registration, uses makeInstance directly if no services
657 * @param desiredLocale the given locale.
658 * @param choice the given style.
659 * @param success Output param filled with success/failure status.
660 * @return A new NumberFormat instance.
662 static NumberFormat
* createInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
665 * Creates the specified decimal format style of the desired locale.
666 * @param desiredLocale the given locale.
667 * @param choice the given style.
668 * @param success Output param filled with success/failure status.
669 * @return A new NumberFormat instance.
671 static NumberFormat
* makeInstance(const Locale
& desiredLocale
, EStyles choice
, UErrorCode
& success
);
672 static const int32_t fgNumberPatternsCount
;
673 static const UChar
* const fgLastResortNumberPatterns
[];
676 int32_t fMaxIntegerDigits
;
677 int32_t fMinIntegerDigits
;
678 int32_t fMaxFractionDigits
;
679 int32_t fMinFractionDigits
;
680 UBool fParseIntegerOnly
;
685 friend class ICUNumberFormatFactory
; // access to makeInstance, EStyles
686 friend class ICUNumberFormatService
;
690 * A NumberFormatFactory is used to register new number formats. The factory
691 * should be able to create any of the predefined formats for each locale it
692 * supports. When registered, the locales it supports extend or override the
693 * locale already supported by ICU.
697 class U_I18N_API NumberFormatFactory
: public UObject
{
701 * Return true if this factory will be visible. Default is true.
702 * If not visible, the locales supported by this factory will not
703 * be listed by getAvailableLocales.
706 virtual UBool
visible(void) const = 0;
709 * Return the locale names directly supported by this factory. The number of names
710 * is returned in count;
713 virtual const UnicodeString
* const getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
716 * Return a number format of the appropriate type. If the locale
717 * is not supported, return null. If the locale is supported, but
718 * the type is not provided by this service, return null. Otherwise
719 * return an appropriate instance of NumberFormat.
722 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
726 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
729 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
732 * True if the locale supported by this factory is visible.
735 const UBool _visible
;
738 * The locale supported by this factory, as a UnicodeString.
747 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
)
749 , _id(locale
.getName())
756 virtual UBool
visible(void) const {
763 virtual const UnicodeString
* const getSupportedIDs(int32_t &count
, UErrorCode
& status
) const
765 if (U_SUCCESS(status
)) {
775 // -------------------------------------
778 NumberFormat::getStaticClassID(void)
779 { return (UClassID
)&fgClassID
; }
782 NumberFormat::isParseIntegerOnly() const
784 return fParseIntegerOnly
;
787 inline UnicodeString
&
788 NumberFormat::format(const Formattable
& obj
,
789 UnicodeString
& appendTo
,
790 UErrorCode
& status
) const {
791 return Format::format(obj
, appendTo
, status
);
796 #endif /* #if !UCONFIG_NO_FORMATTING */