2
* Copyright (C) {1997-2005}, 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"
27
* \brief C++ API: Abstract base class for all number formats.
30
#if !UCONFIG_NO_FORMATTING
32
#include "unicode/unistr.h"
33
#include "unicode/format.h"
34
#include "unicode/unum.h" // UNumberFormatStyle
35
#include "unicode/locid.h"
39
#if !UCONFIG_NO_SERVICE
40
class NumberFormatFactory;
41
class StringEnumeration;
46
typedef const void* URegistryKey;
51
* Abstract base class for all number formats. Provides interface for
52
* formatting and parsing a number. Also provides methods for
53
* determining which locales have number formats, and what their names
56
* NumberFormat helps you to format and parse numbers for any locale.
57
* Your code can be completely independent of the locale conventions
58
* for decimal points, thousands-separators, or even the particular
59
* decimal digits used, or whether the number format is even decimal.
61
* To format a number for the current Locale, use one of the static
65
* double myNumber = 7.0;
66
* UnicodeString myString;
67
* UErrorCode success = U_ZERO_ERROR;
68
* NumberFormat* nf = NumberFormat::createInstance(success)
69
* nf->format(myNumber, myString);
70
* cout << " Example 1: " << myString << endl;
73
* If you are formatting multiple numbers, it is more efficient to get
74
* the format and use it multiple times so that the system doesn't
75
* have to fetch the information about the local language and country
76
* conventions multiple times.
79
* UnicodeString myString;
80
* UErrorCode success = U_ZERO_ERROR;
81
* nf = NumberFormat::createInstance( success );
82
* int32_t a[] = { 123, 3333, -1234567 };
83
* const int32_t a_len = sizeof(a) / sizeof(a[0]);
85
* for (int32_t i = 0; i < a_len; i++) {
86
* nf->format(a[i], myString);
89
* cout << " Example 2: " << myString << endl;
92
* To format a number for a different Locale, specify it in the
93
* call to createInstance().
96
* nf = NumberFormat::createInstance( Locale::FRENCH, success );
99
* You can use a NumberFormat to parse also.
102
* UErrorCode success;
103
* Formattable result(-999); // initialized with error code
104
* nf->parse(myString, result, success);
107
* Use createInstance to get the normal number format for that country.
108
* There are other static factory methods available. Use getCurrency
109
* to get the currency number format for that country. Use getPercent
110
* to get a format for displaying percentages. With this format, a
111
* fraction from 0.53 is displayed as 53%.
113
* You can also control the display of numbers with such methods as
114
* getMinimumFractionDigits. If you want even more control over the
115
* format or parsing, or want to give your users more control, you can
116
* try casting the NumberFormat you get from the factory methods to a
117
* DecimalNumberFormat. This will work for the vast majority of
118
* countries; just remember to put it in a try block in case you
119
* encounter an unusual one.
121
* You can also use forms of the parse and format methods with
122
* ParsePosition and FieldPosition to allow you to:
124
* <li>(a) progressively parse through pieces of a string.
125
* <li>(b) align the decimal point and other areas.
127
* For example, you can align numbers in two ways.
129
* If you are using a monospaced font with spacing for alignment, you
130
* can pass the FieldPosition in your format call, with field =
131
* INTEGER_FIELD. On output, getEndIndex will be set to the offset
132
* between the last character of the integer and the decimal. Add
133
* (desiredSpaceCount - getEndIndex) spaces at the front of the
136
* If you are using proportional fonts, instead of padding with
137
* spaces, measure the width of the string in pixels from the start to
138
* getEndIndex. Then move the pen by (desiredPixelWidth -
139
* widthToAlignmentPoint) before drawing the text. It also works
140
* where there is no decimal, but possibly additional characters at
141
* the end, e.g. with parentheses in negative numbers: "(12)" for -12.
143
* <em>User subclasses are not supported.</em> While clients may write
144
* subclasses, such code will not necessarily work and will not be
145
* guaranteed to work stably from release to release.
149
class U_I18N_API NumberFormat : public Format {
153
* Alignment Field constants used to construct a FieldPosition object.
154
* Signifies that the position of the integer part or fraction part of
155
* a formatted number should be returned.
160
enum EAlignmentFields {
166
* These constants are provided for backwards compatibility only.
167
* Please use the C++ style constants defined above.
170
INTEGER_FIELD = kIntegerField,
171
FRACTION_FIELD = kFractionField
178
virtual ~NumberFormat();
181
* Return true if the given Format objects are semantically equal.
182
* Objects of different subclasses are considered unequal.
183
* @return true if the given Format objects are semantically equal.
186
virtual UBool operator==(const Format& other) const;
189
* Format an object to produce a string. This method handles
190
* Formattable objects with numeric types. If the Formattable
191
* object type is not a numeric type, then it returns a failing
194
* @param obj The object to format.
195
* @param appendTo Output parameter to receive result.
196
* Result is appended to existing contents.
197
* @param pos On input: an alignment field, if desired.
198
* On output: the offsets of the alignment field.
199
* @param status Output param filled with success/failure status.
200
* @return Reference to 'appendTo' parameter.
203
virtual UnicodeString& format(const Formattable& obj,
204
UnicodeString& appendTo,
206
UErrorCode& status) const;
209
* Parse a string to produce an object. This methods handles
210
* parsing of numeric strings into Formattable objects with numeric
213
* Before calling, set parse_pos.index to the offset you want to
214
* start parsing at in the source. After calling, parse_pos.index
215
* indicates the position after the successfully parsed text. If
216
* an error occurs, parse_pos.index is unchanged.
218
* When parsing, leading whitespace is discarded (with successful
219
* parse), while trailing whitespace is left as is.
221
* See Format::parseObject() for more.
223
* @param source The string to be parsed into an object.
224
* @param result Formattable to be set to the parse result.
225
* If parse fails, return contents are undefined.
226
* @param parse_pos The position to start parsing at. Upon return
227
* this param is set to the position after the
228
* last character successfully parsed. If the
229
* source is not parsed successfully, this param
230
* will remain unchanged.
231
* @return A newly created Formattable* object, or NULL
232
* on failure. The caller owns this and should
233
* delete it when done.
236
virtual void parseObject(const UnicodeString& source,
238
ParsePosition& parse_pos) const;
241
* Format a double number. These methods call the NumberFormat
242
* pure virtual format() methods with the default FieldPosition.
244
* @param number The value to be formatted.
245
* @param appendTo Output parameter to receive result.
246
* Result is appended to existing contents.
247
* @return Reference to 'appendTo' parameter.
250
UnicodeString& format( double number,
251
UnicodeString& appendTo) const;
254
* Format a long number. These methods call the NumberFormat
255
* pure virtual format() methods with the default FieldPosition.
257
* @param number The value to be formatted.
258
* @param appendTo Output parameter to receive result.
259
* Result is appended to existing contents.
260
* @return Reference to 'appendTo' parameter.
263
UnicodeString& format( int32_t number,
264
UnicodeString& appendTo) const;
267
* Format an int64 number. These methods call the NumberFormat
268
* pure virtual format() methods with the default FieldPosition.
270
* @param number The value to be formatted.
271
* @param appendTo Output parameter to receive result.
272
* Result is appended to existing contents.
273
* @return Reference to 'appendTo' parameter.
276
UnicodeString& format( int64_t number,
277
UnicodeString& appendTo) const;
280
* Format a double number. Concrete subclasses must implement
281
* these pure virtual methods.
283
* @param number The value to be formatted.
284
* @param appendTo Output parameter to receive result.
285
* Result is appended to existing contents.
286
* @param pos On input: an alignment field, if desired.
287
* On output: the offsets of the alignment field.
288
* @return Reference to 'appendTo' parameter.
291
virtual UnicodeString& format(double number,
292
UnicodeString& appendTo,
293
FieldPosition& pos) const = 0;
295
* Format a long number. Concrete subclasses must implement
296
* these pure virtual methods.
298
* @param number The value to be formatted.
299
* @param appendTo Output parameter to receive result.
300
* Result is appended to existing contents.
301
* @param pos On input: an alignment field, if desired.
302
* On output: the offsets of the alignment field.
303
* @return Reference to 'appendTo' parameter.
306
virtual UnicodeString& format(int32_t number,
307
UnicodeString& appendTo,
308
FieldPosition& pos) const = 0;
311
* Format an int64 number. (Not abstract to retain compatibility
312
* with earlier releases, however subclasses should override this
313
* method as it just delegates to format(int32_t number...);
315
* @param number The value to be formatted.
316
* @param appendTo Output parameter to receive result.
317
* Result is appended to existing contents.
318
* @param pos On input: an alignment field, if desired.
319
* On output: the offsets of the alignment field.
320
* @return Reference to 'appendTo' parameter.
323
virtual UnicodeString& format(int64_t number,
324
UnicodeString& appendTo,
325
FieldPosition& pos) const;
327
* Redeclared Format method.
328
* @param obj The object to be formatted.
329
* @param appendTo Output parameter to receive result.
330
* Result is appended to existing contents.
331
* @param status Output parameter set to a failure error code
332
* when a failure occurs.
333
* @return Reference to 'appendTo' parameter.
336
UnicodeString& format(const Formattable& obj,
337
UnicodeString& appendTo,
338
UErrorCode& status) const;
341
* Return a long if possible (e.g. within range LONG_MAX,
342
* LONG_MAX], and with no decimals), otherwise a double. If
343
* IntegerOnly is set, will stop at a decimal point (or equivalent;
344
* e.g. for rational numbers "1 2/3", will stop after the 1).
346
* If no object can be parsed, index is unchanged, and NULL is
349
* This is a pure virtual which concrete subclasses must implement.
351
* @param text The text to be parsed.
352
* @param result Formattable to be set to the parse result.
353
* If parse fails, return contents are undefined.
354
* @param parsePosition The position to start parsing at on input.
355
* On output, moved to after the last successfully
356
* parse character. On parse failure, does not change.
357
* @return A Formattable object of numeric type. The caller
358
* owns this an must delete it. NULL on failure.
361
virtual void parse(const UnicodeString& text,
363
ParsePosition& parsePosition) const = 0;
366
* Parse a string as a numeric value, and return a Formattable
367
* numeric object. This method parses integers only if IntegerOnly
370
* @param text The text to be parsed.
371
* @param result Formattable to be set to the parse result.
372
* If parse fails, return contents are undefined.
373
* @param status Output parameter set to a failure error code
374
* when a failure occurs.
375
* @return A Formattable object of numeric type. The caller
376
* owns this an must delete it. NULL on failure.
377
* @see NumberFormat::isParseIntegerOnly
380
virtual void parse( const UnicodeString& text,
382
UErrorCode& status) const;
385
* Parses text from the given string as a currency amount. Unlike
386
* the parse() method, this method will attempt to parse a generic
387
* currency name, searching for a match of this object's locale's
388
* currency display names, or for a 3-letter ISO currency code.
389
* This method will fail if this format is not a currency format,
390
* that is, if it does not contain the currency pattern symbol
391
* (U+00A4) in its prefix or suffix.
393
* @param text the string to parse
394
* @param result output parameter to receive result. This will have
395
* its currency set to the parsed ISO currency code.
396
* @param pos input-output position; on input, the position within
397
* text to match; must have 0 <= pos.getIndex() < text.length();
398
* on output, the position after the last matched character. If
399
* the parse fails, the position in unchanged upon output.
400
* @return a reference to result
403
virtual Formattable& parseCurrency(const UnicodeString& text,
405
ParsePosition& pos) const;
408
* Return true if this format will parse numbers as integers
409
* only. For example in the English locale, with ParseIntegerOnly
410
* true, the string "1234." would be parsed as the integer value
411
* 1234 and parsing would stop at the "." character. Of course,
412
* the exact format accepted by the parse operation is locale
413
* dependant and determined by sub-classes of NumberFormat.
414
* @return true if this format will parse numbers as integers
418
UBool isParseIntegerOnly(void) const;
421
* Sets whether or not numbers should be parsed as integers only.
422
* @param value set True, this format will parse numbers as integers
424
* @see isParseIntegerOnly
427
virtual void setParseIntegerOnly(UBool value);
430
* Returns the default number format for the current default
431
* locale. The default format is one of the styles provided by
432
* the other factory methods: getNumberInstance,
433
* getCurrencyInstance or getPercentInstance. Exactly which one
434
* is locale dependant.
437
static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
440
* Returns the default number format for the specified locale.
441
* The default format is one of the styles provided by the other
442
* factory methods: getNumberInstance, getCurrencyInstance or
443
* getPercentInstance. Exactly which one is locale dependant.
444
* @param inLocale the given locale.
447
static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
451
* Returns a currency format for the current default locale.
454
static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
457
* Returns a currency format for the specified locale.
458
* @param inLocale the given locale.
461
static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
465
* Returns a percentage format for the current default locale.
468
static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
471
* Returns a percentage format for the specified locale.
472
* @param inLocale the given locale.
475
static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
479
* Returns a scientific format for the current default locale.
482
static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
485
* Returns a scientific format for the specified locale.
486
* @param inLocale the given locale.
489
static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
493
* Get the set of Locales for which NumberFormats are installed.
494
* @param count Output param to receive the size of the locales
497
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
499
#if !UCONFIG_NO_SERVICE
501
* Register a new NumberFormatFactory. The factory will be adopted.
502
* @param toAdopt the NumberFormatFactory instance to be adopted
503
* @param status the in/out status code, no special meanings are assigned
504
* @return a registry key that can be used to unregister this factory
507
static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
510
* Unregister a previously-registered NumberFormatFactory using the key returned from the
511
* register call. Key becomes invalid after a successful call and should not be used again.
512
* The NumberFormatFactory corresponding to the key will be deleted.
513
* @param key the registry key returned by a previous call to registerFactory
514
* @param status the in/out status code, no special meanings are assigned
515
* @return TRUE if the factory for the key was successfully unregistered
518
static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
521
* Return a StringEnumeration over the locales available at the time of the call,
522
* including registered locales.
523
* @return a StringEnumeration over the locales available at the time of the call
526
static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
527
#endif /* UCONFIG_NO_SERVICE */
530
* Returns true if grouping is used in this format. For example,
531
* in the English locale, with grouping on, the number 1234567
532
* might be formatted as "1,234,567". The grouping separator as
533
* well as the size of each group is locale dependant and is
534
* determined by sub-classes of NumberFormat.
535
* @see setGroupingUsed
538
UBool isGroupingUsed(void) const;
541
* Set whether or not grouping will be used in this format.
542
* @param newValue True, grouping will be used in this format.
543
* @see getGroupingUsed
546
virtual void setGroupingUsed(UBool newValue);
549
* Returns the maximum number of digits allowed in the integer portion of a
551
* @return the maximum number of digits allowed in the integer portion of a
553
* @see setMaximumIntegerDigits
556
int32_t getMaximumIntegerDigits(void) const;
559
* Sets the maximum number of digits allowed in the integer portion of a
560
* number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
561
* new value for maximumIntegerDigits is less than the current value
562
* of minimumIntegerDigits, then minimumIntegerDigits will also be set to
565
* @param newValue the new value for the maximum number of digits
566
* allowed in the integer portion of a number.
567
* @see getMaximumIntegerDigits
570
virtual void setMaximumIntegerDigits(int32_t newValue);
573
* Returns the minimum number of digits allowed in the integer portion of a
575
* @return the minimum number of digits allowed in the integer portion of a
577
* @see setMinimumIntegerDigits
580
int32_t getMinimumIntegerDigits(void) const;
583
* Sets the minimum number of digits allowed in the integer portion of a
584
* number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
585
* new value for minimumIntegerDigits exceeds the current value
586
* of maximumIntegerDigits, then maximumIntegerDigits will also be set to
588
* @param newValue the new value to be set.
589
* @see getMinimumIntegerDigits
592
virtual void setMinimumIntegerDigits(int32_t newValue);
595
* Returns the maximum number of digits allowed in the fraction portion of a
597
* @return the maximum number of digits allowed in the fraction portion of a
599
* @see setMaximumFractionDigits
602
int32_t getMaximumFractionDigits(void) const;
605
* Sets the maximum number of digits allowed in the fraction portion of a
606
* number. maximumFractionDigits must be >= minimumFractionDigits. If the
607
* new value for maximumFractionDigits is less than the current value
608
* of minimumFractionDigits, then minimumFractionDigits will also be set to
610
* @param newValue the new value to be set.
611
* @see getMaximumFractionDigits
614
virtual void setMaximumFractionDigits(int32_t newValue);
617
* Returns the minimum number of digits allowed in the fraction portion of a
619
* @return the minimum number of digits allowed in the fraction portion of a
621
* @see setMinimumFractionDigits
624
int32_t getMinimumFractionDigits(void) const;
627
* Sets the minimum number of digits allowed in the fraction portion of a
628
* number. minimumFractionDigits must be <= maximumFractionDigits. If the
629
* new value for minimumFractionDigits exceeds the current value
630
* of maximumFractionDigits, then maximumIntegerDigits will also be set to
632
* @param newValue the new value to be set.
633
* @see getMinimumFractionDigits
636
virtual void setMinimumFractionDigits(int32_t newValue);
639
* Sets the currency used to display currency
640
* amounts. This takes effect immediately, if this format is a
641
* currency format. If this format is not a currency format, then
642
* the currency is used if and when this object becomes a
644
* @param theCurrency a 3-letter ISO code indicating new currency
645
* to use. It need not be null-terminated. May be the empty
646
* string or NULL to indicate no currency.
647
* @param ec input-output error code
650
virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec);
653
* Gets the currency used to display currency
654
* amounts. This may be an empty string for some subclasses.
655
* @return a 3-letter null-terminated ISO code indicating
656
* the currency in use, or a pointer to the empty string.
659
const UChar* getCurrency() const;
664
* Return the class ID for this class. This is useful for
665
* comparing to a return value from getDynamicClassID(). Note that,
666
* because NumberFormat is an abstract base class, no fully constructed object
667
* will have the class ID returned by NumberFormat::getStaticClassID().
668
* @return The class ID for all objects of this class.
671
static UClassID U_EXPORT2 getStaticClassID(void);
674
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
675
* This method is to implement a simple version of RTTI, since not all
676
* C++ compilers support genuine RTTI. Polymorphic operator==() and
677
* clone() methods call this method.
679
* @return The class ID for this object. All objects of a
680
* given class have the same class ID. Objects of
681
* other classes have different class IDs.
684
virtual UClassID getDynamicClassID(void) const = 0;
689
* Default constructor for subclass use only.
698
NumberFormat(const NumberFormat&);
701
* Assignment operator.
704
NumberFormat& operator=(const NumberFormat&);
707
* Returns the currency in effect for this formatter. Subclasses
708
* should override this method as needed. Unlike getCurrency(),
709
* this method should never return "".
710
* @result output parameter for null-terminated result, which must
711
* have a capacity of at least 4
714
virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const;
723
kStyleCount // ALWAYS LAST ENUM: number of styles
727
* Creates the specified decimal format style of the desired locale.
728
* Hook for service registration, uses makeInstance directly if no services
730
* @param desiredLocale the given locale.
731
* @param choice the given style.
732
* @param success Output param filled with success/failure status.
733
* @return A new NumberFormat instance.
735
static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
738
* Creates the specified decimal format style of the desired locale.
739
* @param desiredLocale the given locale.
740
* @param choice the given style.
741
* @param success Output param filled with success/failure status.
742
* @return A new NumberFormat instance.
744
static NumberFormat* makeInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
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 */