• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ********************************************************************************
5 * Copyright (C) 1997-2016, International Business Machines Corporation and others.
6 * All Rights Reserved.
7 ********************************************************************************
8 *
9 * File NUMFMT.H
10 *
11 * Modification History:
12 *
13 *   Date        Name        Description
14 *   02/19/97    aliu        Converted from java.
15 *   03/18/97    clhuang     Updated per C++ implementation.
16 *   04/17/97    aliu        Changed DigitCount to int per code review.
17 *    07/20/98    stephen        JDK 1.2 sync up. Added scientific support.
18 *                            Changed naming conventions to match C++ guidelines
19 *                            Derecated Java style constants (eg, INTEGER_FIELD)
20 ********************************************************************************
21 */
22 
23 #ifndef NUMFMT_H
24 #define NUMFMT_H
25 
26 
27 #include "unicode/utypes.h"
28 
29 /**
30  * \file
31  * \brief C++ API: Abstract base class for all number formats.
32  */
33 
34 #if !UCONFIG_NO_FORMATTING
35 
36 #include "unicode/unistr.h"
37 #include "unicode/format.h"
38 #include "unicode/unum.h" // UNumberFormatStyle
39 #include "unicode/locid.h"
40 #include "unicode/stringpiece.h"
41 #include "unicode/curramt.h"
42 #include "unicode/udisplaycontext.h"
43 
44 class NumberFormatTest;
45 
46 U_NAMESPACE_BEGIN
47 
48 class SharedNumberFormat;
49 
50 #if !UCONFIG_NO_SERVICE
51 class NumberFormatFactory;
52 class StringEnumeration;
53 #endif
54 
55 /**
56  *
57  * Abstract base class for all number formats.  Provides interface for
58  * formatting and parsing a number.  Also provides methods for
59  * determining which locales have number formats, and what their names
60  * are.
61  * \headerfile unicode/numfmt.h "unicode/numfmt.h"
62  * <P>
63  * NumberFormat helps you to format and parse numbers for any locale.
64  * Your code can be completely independent of the locale conventions
65  * for decimal points, thousands-separators, or even the particular
66  * decimal digits used, or whether the number format is even decimal.
67  * <P>
68  * To format a number for the current Locale, use one of the static
69  * factory methods:
70  * \code
71  *    #include <iostream>
72  *    #include "unicode/numfmt.h"
73  *    #include "unicode/unistr.h"
74  *    #include "unicode/ustream.h"
75  *    using namespace std;
76  *
77  *    int main() {
78  *        double myNumber = 7.0;
79  *        UnicodeString myString;
80  *        UErrorCode success = U_ZERO_ERROR;
81  *        NumberFormat* nf = NumberFormat::createInstance(success);
82  *        nf->format(myNumber, myString);
83  *        cout << " Example 1: " << myString << endl;
84  *    }
85  * \endcode
86  * Note that there are additional factory methods within subclasses of
87  * NumberFormat.
88  * <P>
89  * If you are formatting multiple numbers, it is more efficient to get
90  * the format and use it multiple times so that the system doesn't
91  * have to fetch the information about the local language and country
92  * conventions multiple times.
93  * \code
94  *     UnicodeString myString;
95  *     UErrorCode success = U_ZERO_ERROR;
96  *     NumberFormat *nf = NumberFormat::createInstance( success );
97  *     for (int32_t number: {123, 3333, -1234567}) {
98  *         nf->format(number, myString);
99  *         myString += "; ";
100  *     }
101  *     cout << " Example 2: " << myString << endl;
102  * \endcode
103  * To format a number for a different Locale, specify it in the
104  * call to \c createInstance().
105  * \code
106  *     nf = NumberFormat::createInstance(Locale::getFrench(), success);
107  * \endcode
108  * You can use a \c NumberFormat to parse also.
109  * \code
110  *    UErrorCode success;
111  *    Formattable result(-999);  // initialized with error code
112  *    nf->parse(myString, result, success);
113  * \endcode
114  * Use \c createInstance() to get the normal number format for a \c Locale.
115  * There are other static factory methods available.  Use \c createCurrencyInstance()
116  * to get the currency number format for that country.  Use \c createPercentInstance()
117  * to get a format for displaying percentages. With this format, a
118  * fraction from 0.53 is displayed as 53%.
119  * <P>
120  * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance().
121  * For example, use\n
122  * \c createInstance(locale, UNUM_DECIMAL, errorCode) to get the normal number format,\n
123  * \c createInstance(locale, UNUM_PERCENT, errorCode) to get a format for displaying percentage,\n
124  * \c createInstance(locale, UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,\n
125  * \c createInstance(locale, UNUM_CURRENCY, errorCode) to get the currency number format,
126  * in which the currency is represented by its symbol, for example, "$3.00".\n
127  * \c createInstance(locale, UNUM_CURRENCY_ISO, errorCode)  to get the currency number format,
128  * in which the currency is represented by its ISO code, for example "USD3.00".\n
129  * \c createInstance(locale, UNUM_CURRENCY_PLURAL, errorCode) to get the currency number format,
130  * in which the currency is represented by its full name in plural format,
131  * for example, "3.00 US dollars" or "1.00 US dollar".
132  * <P>
133  * You can also control the display of numbers with such methods as
134  * \c getMinimumFractionDigits().  If you want even more control over the
135  * format or parsing, or want to give your users more control, you can
136  * try dynamic_casting the \c NumberFormat you get from the factory methods to a
137  * \c DecimalFormat. This will work for the vast majority of
138  * countries; just remember to test for NULL in case you
139  * encounter an unusual one.
140  * <P>
141  * You can also use forms of the parse and format methods with
142  * \c ParsePosition and \c FieldPosition to allow you to:
143  * <ul type=round>
144  *   <li>(a) progressively parse through pieces of a string.
145  *   <li>(b) align the decimal point and other areas.
146  * </ul>
147  * For example, you can align numbers in two ways.
148  * <P>
149  * If you are using a monospaced font with spacing for alignment, you
150  * can pass the \c FieldPosition in your format call, with field =
151  * \c UNUM_INTEGER_FIELD. On output, \c getEndIndex will be set to the offset
152  * between the last character of the integer and the decimal. Add
153  * (desiredSpaceCount - getEndIndex) spaces at the front of the
154  * string.
155  * <P>
156  * If you are using proportional fonts, instead of padding with
157  * spaces, measure the width of the string in pixels from the start to
158  * getEndIndex.  Then move the pen by (desiredPixelWidth -
159  * widthToAlignmentPoint) before drawing the text.  It also works
160  * where there is no decimal, but possibly additional characters at
161  * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
162  * <p>
163  * <em>User subclasses are not supported.</em> While clients may write
164  * subclasses, such code will not necessarily work and will not be
165  * guaranteed to work stably from release to release.
166  *
167  * @stable ICU 2.0
168  */
169 class U_I18N_API NumberFormat : public Format {
170 public:
171     /**
172      * Alignment Field constants used to construct a FieldPosition object.
173      * Signifies that the position of the integer part or fraction part of
174      * a formatted number should be returned.
175      *
176      * Note: as of ICU 4.4, the values in this enum have been extended to
177      * support identification of all number format fields, not just those
178      * pertaining to alignment.
179      *
180      * These constants are provided for backwards compatibility only.
181      * Please use the C style constants defined in the header file unum.h.
182      *
183      * @see FieldPosition
184      * @stable ICU 2.0
185      */
186     enum EAlignmentFields {
187         /** @stable ICU 2.0 */
188         kIntegerField = UNUM_INTEGER_FIELD,
189         /** @stable ICU 2.0 */
190         kFractionField = UNUM_FRACTION_FIELD,
191         /** @stable ICU 2.0 */
192         kDecimalSeparatorField = UNUM_DECIMAL_SEPARATOR_FIELD,
193         /** @stable ICU 2.0 */
194         kExponentSymbolField = UNUM_EXPONENT_SYMBOL_FIELD,
195         /** @stable ICU 2.0 */
196         kExponentSignField = UNUM_EXPONENT_SIGN_FIELD,
197         /** @stable ICU 2.0 */
198         kExponentField = UNUM_EXPONENT_FIELD,
199         /** @stable ICU 2.0 */
200         kGroupingSeparatorField = UNUM_GROUPING_SEPARATOR_FIELD,
201         /** @stable ICU 2.0 */
202         kCurrencyField = UNUM_CURRENCY_FIELD,
203         /** @stable ICU 2.0 */
204         kPercentField = UNUM_PERCENT_FIELD,
205         /** @stable ICU 2.0 */
206         kPermillField = UNUM_PERMILL_FIELD,
207         /** @stable ICU 2.0 */
208         kSignField = UNUM_SIGN_FIELD,
209 
210     /**
211      * These constants are provided for backwards compatibility only.
212      * Please use the constants defined in the header file unum.h.
213      */
214         /** @stable ICU 2.0 */
215         INTEGER_FIELD        = UNUM_INTEGER_FIELD,
216         /** @stable ICU 2.0 */
217         FRACTION_FIELD       = UNUM_FRACTION_FIELD
218     };
219 
220     /**
221      * Destructor.
222      * @stable ICU 2.0
223      */
224     virtual ~NumberFormat();
225 
226     /**
227      * Return true if the given Format objects are semantically equal.
228      * Objects of different subclasses are considered unequal.
229      * @return    true if the given Format objects are semantically equal.
230      * @stable ICU 2.0
231      */
232     virtual UBool operator==(const Format& other) const;
233 
234 
235     using Format::format;
236 
237     /**
238      * Format an object to produce a string.  This method handles
239      * Formattable objects with numeric types. If the Formattable
240      * object type is not a numeric type, then it returns a failing
241      * UErrorCode.
242      *
243      * @param obj       The object to format.
244      * @param appendTo  Output parameter to receive result.
245      *                  Result is appended to existing contents.
246      * @param pos       On input: an alignment field, if desired.
247      *                  On output: the offsets of the alignment field.
248      * @param status    Output param filled with success/failure status.
249      * @return          Reference to 'appendTo' parameter.
250      * @stable ICU 2.0
251      */
252     virtual UnicodeString& format(const Formattable& obj,
253                                   UnicodeString& appendTo,
254                                   FieldPosition& pos,
255                                   UErrorCode& status) const;
256 
257     /**
258      * Format an object to produce a string.  This method handles
259      * Formattable objects with numeric types. If the Formattable
260      * object type is not a numeric type, then it returns a failing
261      * UErrorCode.
262      *
263      * @param obj       The object to format.
264      * @param appendTo  Output parameter to receive result.
265      *                  Result is appended to existing contents.
266      * @param posIter   On return, can be used to iterate over positions
267      *                  of fields generated by this format call.  Can be
268      *                  NULL.
269      * @param status    Output param filled with success/failure status.
270      * @return          Reference to 'appendTo' parameter.
271      * @stable ICU 4.4
272      */
273     virtual UnicodeString& format(const Formattable& obj,
274                                   UnicodeString& appendTo,
275                                   FieldPositionIterator* posIter,
276                                   UErrorCode& status) const;
277 
278     /**
279      * Parse a string to produce an object.  This methods handles
280      * parsing of numeric strings into Formattable objects with numeric
281      * types.
282      * <P>
283      * Before calling, set parse_pos.index to the offset you want to
284      * start parsing at in the source. After calling, parse_pos.index
285      * indicates the position after the successfully parsed text.  If
286      * an error occurs, parse_pos.index is unchanged.
287      * <P>
288      * When parsing, leading whitespace is discarded (with successful
289      * parse), while trailing whitespace is left as is.
290      * <P>
291      * See Format::parseObject() for more.
292      *
293      * @param source    The string to be parsed into an object.
294      * @param result    Formattable to be set to the parse result.
295      *                  If parse fails, return contents are undefined.
296      * @param parse_pos The position to start parsing at. Upon return
297      *                  this param is set to the position after the
298      *                  last character successfully parsed. If the
299      *                  source is not parsed successfully, this param
300      *                  will remain unchanged.
301      * @return          A newly created Formattable* object, or NULL
302      *                  on failure.  The caller owns this and should
303      *                  delete it when done.
304      * @stable ICU 2.0
305      */
306     virtual void parseObject(const UnicodeString& source,
307                              Formattable& result,
308                              ParsePosition& parse_pos) const;
309 
310     /**
311      * Format a double number. These methods call the NumberFormat
312      * pure virtual format() methods with the default FieldPosition.
313      *
314      * @param number    The value to be formatted.
315      * @param appendTo  Output parameter to receive result.
316      *                  Result is appended to existing contents.
317      * @return          Reference to 'appendTo' parameter.
318      * @stable ICU 2.0
319      */
320     UnicodeString& format(  double number,
321                             UnicodeString& appendTo) const;
322 
323     /**
324      * Format a long number. These methods call the NumberFormat
325      * pure virtual format() methods with the default FieldPosition.
326      *
327      * @param number    The value to be formatted.
328      * @param appendTo  Output parameter to receive result.
329      *                  Result is appended to existing contents.
330      * @return          Reference to 'appendTo' parameter.
331      * @stable ICU 2.0
332      */
333     UnicodeString& format(  int32_t number,
334                             UnicodeString& appendTo) const;
335 
336     /**
337      * Format an int64 number. These methods call the NumberFormat
338      * pure virtual format() methods with the default FieldPosition.
339      *
340      * @param number    The value to be formatted.
341      * @param appendTo  Output parameter to receive result.
342      *                  Result is appended to existing contents.
343      * @return          Reference to 'appendTo' parameter.
344      * @stable ICU 2.8
345      */
346     UnicodeString& format(  int64_t number,
347                             UnicodeString& appendTo) const;
348 
349     /**
350      * Format a double number. Concrete subclasses must implement
351      * these pure virtual methods.
352      *
353      * @param number    The value to be formatted.
354      * @param appendTo  Output parameter to receive result.
355      *                  Result is appended to existing contents.
356      * @param pos       On input: an alignment field, if desired.
357      *                  On output: the offsets of the alignment field.
358      * @return          Reference to 'appendTo' parameter.
359      * @stable ICU 2.0
360      */
361     virtual UnicodeString& format(double number,
362                                   UnicodeString& appendTo,
363                                   FieldPosition& pos) const = 0;
364     /**
365      * Format a double number. By default, the parent function simply
366      * calls the base class and does not return an error status.
367      * Therefore, the status may be ignored in some subclasses.
368      *
369      * @param number    The value to be formatted.
370      * @param appendTo  Output parameter to receive result.
371      *                  Result is appended to existing contents.
372      * @param pos       On input: an alignment field, if desired.
373      *                  On output: the offsets of the alignment field.
374      * @param status    error status
375      * @return          Reference to 'appendTo' parameter.
376      * @internal
377      */
378     virtual UnicodeString& format(double number,
379                                   UnicodeString& appendTo,
380                                   FieldPosition& pos,
381                                   UErrorCode &status) const;
382     /**
383      * Format a double number. Subclasses must implement
384      * this method.
385      *
386      * @param number    The value to be formatted.
387      * @param appendTo  Output parameter to receive result.
388      *                  Result is appended to existing contents.
389      * @param posIter   On return, can be used to iterate over positions
390      *                  of fields generated by this format call.
391      *                  Can be NULL.
392      * @param status    Output param filled with success/failure status.
393      * @return          Reference to 'appendTo' parameter.
394      * @stable ICU 4.4
395      */
396     virtual UnicodeString& format(double number,
397                                   UnicodeString& appendTo,
398                                   FieldPositionIterator* posIter,
399                                   UErrorCode& status) const;
400     /**
401      * Format a long number. Concrete subclasses must implement
402      * these pure virtual methods.
403      *
404      * @param number    The value to be formatted.
405      * @param appendTo  Output parameter to receive result.
406      *                  Result is appended to existing contents.
407      * @param pos       On input: an alignment field, if desired.
408      *                  On output: the offsets of the alignment field.
409      * @return          Reference to 'appendTo' parameter.
410      * @stable ICU 2.0
411     */
412     virtual UnicodeString& format(int32_t number,
413                                   UnicodeString& appendTo,
414                                   FieldPosition& pos) const = 0;
415 
416     /**
417      * Format a long number. Concrete subclasses may override
418      * this function to provide status return.
419      *
420      * @param number    The value to be formatted.
421      * @param appendTo  Output parameter to receive result.
422      *                  Result is appended to existing contents.
423      * @param pos       On input: an alignment field, if desired.
424      *                  On output: the offsets of the alignment field.
425      * @param status the output status.
426      * @return          Reference to 'appendTo' parameter.
427      * @internal
428     */
429     virtual UnicodeString& format(int32_t number,
430                                   UnicodeString& appendTo,
431                                   FieldPosition& pos,
432                                   UErrorCode &status) const;
433 
434     /**
435      * Format an int32 number. Subclasses must implement
436      * this method.
437      *
438      * @param number    The value to be formatted.
439      * @param appendTo  Output parameter to receive result.
440      *                  Result is appended to existing contents.
441      * @param posIter   On return, can be used to iterate over positions
442      *                  of fields generated by this format call.
443      *                  Can be NULL.
444      * @param status    Output param filled with success/failure status.
445      * @return          Reference to 'appendTo' parameter.
446      * @stable ICU 4.4
447      */
448     virtual UnicodeString& format(int32_t number,
449                                   UnicodeString& appendTo,
450                                   FieldPositionIterator* posIter,
451                                   UErrorCode& status) const;
452     /**
453      * Format an int64 number. (Not abstract to retain compatibility
454      * with earlier releases, however subclasses should override this
455      * method as it just delegates to format(int32_t number...);
456      *
457      * @param number    The value to be formatted.
458      * @param appendTo  Output parameter to receive result.
459      *                  Result is appended to existing contents.
460      * @param pos       On input: an alignment field, if desired.
461      *                  On output: the offsets of the alignment field.
462      * @return          Reference to 'appendTo' parameter.
463      * @stable ICU 2.8
464     */
465     virtual UnicodeString& format(int64_t number,
466                                   UnicodeString& appendTo,
467                                   FieldPosition& pos) const;
468 
469     /**
470      * Format an int64 number. (Not abstract to retain compatibility
471      * with earlier releases, however subclasses should override this
472      * method as it just delegates to format(int32_t number...);
473      *
474      * @param number    The value to be formatted.
475      * @param appendTo  Output parameter to receive result.
476      *                  Result is appended to existing contents.
477      * @param pos       On input: an alignment field, if desired.
478      *                  On output: the offsets of the alignment field.
479      * @param status    Output param filled with success/failure status.
480      * @return          Reference to 'appendTo' parameter.
481      * @internal
482     */
483     virtual UnicodeString& format(int64_t number,
484                                   UnicodeString& appendTo,
485                                   FieldPosition& pos,
486                                   UErrorCode& status) const;
487     /**
488      * Format an int64 number. Subclasses must implement
489      * this method.
490      *
491      * @param number    The value to be formatted.
492      * @param appendTo  Output parameter to receive result.
493      *                  Result is appended to existing contents.
494      * @param posIter   On return, can be used to iterate over positions
495      *                  of fields generated by this format call.
496      *                  Can be NULL.
497      * @param status    Output param filled with success/failure status.
498      * @return          Reference to 'appendTo' parameter.
499      * @stable ICU 4.4
500      */
501     virtual UnicodeString& format(int64_t number,
502                                   UnicodeString& appendTo,
503                                   FieldPositionIterator* posIter,
504                                   UErrorCode& status) const;
505 
506     /**
507      * Format a decimal number. Subclasses must implement
508      * this method.  The syntax of the unformatted number is a "numeric string"
509      * as defined in the Decimal Arithmetic Specification, available at
510      * http://speleotrove.com/decimal
511      *
512      * @param number    The unformatted number, as a string, to be formatted.
513      * @param appendTo  Output parameter to receive result.
514      *                  Result is appended to existing contents.
515      * @param posIter   On return, can be used to iterate over positions
516      *                  of fields generated by this format call.
517      *                  Can be NULL.
518      * @param status    Output param filled with success/failure status.
519      * @return          Reference to 'appendTo' parameter.
520      * @stable ICU 4.4
521      */
522     virtual UnicodeString& format(StringPiece number,
523                                   UnicodeString& appendTo,
524                                   FieldPositionIterator* posIter,
525                                   UErrorCode& status) const;
526 public:
527     /**
528      * Format a decimal number.
529      * The number is a DigitList wrapper onto a floating point decimal number.
530      * The default implementation in NumberFormat converts the decimal number
531      * to a double and formats that.  Subclasses of NumberFormat that want
532      * to specifically handle big decimal numbers must override this method.
533      * class DecimalFormat does so.
534      *
535      * @param number    The number, a DigitList format Decimal Floating Point.
536      * @param appendTo  Output parameter to receive result.
537      *                  Result is appended to existing contents.
538      * @param posIter   On return, can be used to iterate over positions
539      *                  of fields generated by this format call.
540      * @param status    Output param filled with success/failure status.
541      * @return          Reference to 'appendTo' parameter.
542      * @internal
543      */
544     virtual UnicodeString& format(const DigitList &number,
545                                   UnicodeString& appendTo,
546                                   FieldPositionIterator* posIter,
547                                   UErrorCode& status) const;
548 
549     /**
550      * Format a decimal number.
551      * The number is a DigitList wrapper onto a floating point decimal number.
552      * The default implementation in NumberFormat converts the decimal number
553      * to a double and formats that.  Subclasses of NumberFormat that want
554      * to specifically handle big decimal numbers must override this method.
555      * class DecimalFormat does so.
556      *
557      * @param number    The number, a DigitList format Decimal Floating Point.
558      * @param appendTo  Output parameter to receive result.
559      *                  Result is appended to existing contents.
560      * @param pos       On input: an alignment field, if desired.
561      *                  On output: the offsets of the alignment field.
562      * @param status    Output param filled with success/failure status.
563      * @return          Reference to 'appendTo' parameter.
564      * @internal
565      */
566     virtual UnicodeString& format(const DigitList &number,
567                                   UnicodeString& appendTo,
568                                   FieldPosition& pos,
569                                   UErrorCode& status) const;
570 
571 public:
572 
573    /**
574     * Return a long if possible (e.g. within range LONG_MAX,
575     * LONG_MAX], and with no decimals), otherwise a double.  If
576     * IntegerOnly is set, will stop at a decimal point (or equivalent;
577     * e.g. for rational numbers "1 2/3", will stop after the 1).
578     * <P>
579     * If no object can be parsed, index is unchanged, and NULL is
580     * returned.
581     * <P>
582     * This is a pure virtual which concrete subclasses must implement.
583     *
584     * @param text           The text to be parsed.
585     * @param result         Formattable to be set to the parse result.
586     *                       If parse fails, return contents are undefined.
587     * @param parsePosition  The position to start parsing at on input.
588     *                       On output, moved to after the last successfully
589     *                       parse character. On parse failure, does not change.
590     * @stable ICU 2.0
591     */
592     virtual void parse(const UnicodeString& text,
593                        Formattable& result,
594                        ParsePosition& parsePosition) const = 0;
595 
596     /**
597      * Parse a string as a numeric value, and return a Formattable
598      * numeric object. This method parses integers only if IntegerOnly
599      * is set.
600      *
601      * @param text          The text to be parsed.
602      * @param result        Formattable to be set to the parse result.
603      *                      If parse fails, return contents are undefined.
604      * @param status        Output parameter set to a failure error code
605      *                      when a failure occurs.
606      * @see                 NumberFormat::isParseIntegerOnly
607      * @stable ICU 2.0
608      */
609     virtual void parse(const UnicodeString& text,
610                        Formattable& result,
611                        UErrorCode& status) const;
612 
613     /**
614      * Parses text from the given string as a currency amount.  Unlike
615      * the parse() method, this method will attempt to parse a generic
616      * currency name, searching for a match of this object's locale's
617      * currency display names, or for a 3-letter ISO currency code.
618      * This method will fail if this format is not a currency format,
619      * that is, if it does not contain the currency pattern symbol
620      * (U+00A4) in its prefix or suffix.
621      *
622      * @param text the string to parse
623      * @param pos  input-output position; on input, the position within text
624      *             to match; must have 0 <= pos.getIndex() < text.length();
625      *             on output, the position after the last matched character.
626      *             If the parse fails, the position in unchanged upon output.
627      * @return     if parse succeeds, a pointer to a newly-created CurrencyAmount
628      *             object (owned by the caller) containing information about
629      *             the parsed currency; if parse fails, this is NULL.
630      * @stable ICU 49
631      */
632     virtual CurrencyAmount* parseCurrency(const UnicodeString& text,
633                                           ParsePosition& pos) const;
634 
635     /**
636      * Return true if this format will parse numbers as integers
637      * only.  For example in the English locale, with ParseIntegerOnly
638      * true, the string "1234." would be parsed as the integer value
639      * 1234 and parsing would stop at the "." character.  Of course,
640      * the exact format accepted by the parse operation is locale
641      * dependant and determined by sub-classes of NumberFormat.
642      * @return    true if this format will parse numbers as integers
643      *            only.
644      * @stable ICU 2.0
645      */
646     UBool isParseIntegerOnly(void) const;
647 
648     /**
649      * Sets whether or not numbers should be parsed as integers only.
650      * @param value    set True, this format will parse numbers as integers
651      *                 only.
652      * @see isParseIntegerOnly
653      * @stable ICU 2.0
654      */
655     virtual void setParseIntegerOnly(UBool value);
656 
657     /**
658      * Sets whether lenient parsing should be enabled (it is off by default).
659      *
660      * @param enable \c TRUE if lenient parsing should be used,
661      *               \c FALSE otherwise.
662      * @stable ICU 4.8
663      */
664     virtual void setLenient(UBool enable);
665 
666     /**
667      * Returns whether lenient parsing is enabled (it is off by default).
668      *
669      * @return \c TRUE if lenient parsing is enabled,
670      *         \c FALSE otherwise.
671      * @see #setLenient
672      * @stable ICU 4.8
673      */
674     virtual UBool isLenient(void) const;
675 
676     /**
677      * Create a default style NumberFormat for the current default locale.
678      * The default formatting style is locale dependent.
679      * @stable ICU 2.0
680      */
681     static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
682 
683     /**
684      * Create a default style NumberFormat for the specified locale.
685      * The default formatting style is locale dependent.
686      * @param inLocale    the given locale.
687      * @stable ICU 2.0
688      */
689     static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
690                                         UErrorCode&);
691 
692     /**
693      * Create a specific style NumberFormat for the specified locale.
694      * @param desiredLocale    the given locale.
695      * @param style            the given style.
696      * @param errorCode        Output param filled with success/failure status.
697      * @return                 A new NumberFormat instance.
698      * @stable ICU 4.8
699      */
700     static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale,
701                                                   UNumberFormatStyle style,
702                                                   UErrorCode& errorCode);
703 
704 #ifndef U_HIDE_INTERNAL_API
705 
706     /**
707      * ICU use only.
708      * Creates NumberFormat instance without using the cache.
709      * @internal
710      */
711     static NumberFormat* internalCreateInstance(
712             const Locale& desiredLocale,
713             UNumberFormatStyle style,
714             UErrorCode& errorCode);
715 
716     /**
717      * ICU use only.
718      * Returns handle to the shared, cached NumberFormat instance for given
719      * locale. On success, caller must call removeRef() on returned value
720      * once it is done with the shared instance.
721      * @internal
722      */
723     static const SharedNumberFormat* U_EXPORT2 createSharedInstance(
724             const Locale& inLocale, UNumberFormatStyle style, UErrorCode& status);
725 
726 #endif  /* U_HIDE_INTERNAL_API */
727 
728     /**
729      * Returns a currency format for the current default locale.
730      * @stable ICU 2.0
731      */
732     static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
733 
734     /**
735      * Returns a currency format for the specified locale.
736      * @param inLocale    the given locale.
737      * @stable ICU 2.0
738      */
739     static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
740                                                 UErrorCode&);
741 
742     /**
743      * Returns a percentage format for the current default locale.
744      * @stable ICU 2.0
745      */
746     static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
747 
748     /**
749      * Returns a percentage format for the specified locale.
750      * @param inLocale    the given locale.
751      * @stable ICU 2.0
752      */
753     static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
754                                                UErrorCode&);
755 
756     /**
757      * Returns a scientific format for the current default locale.
758      * @stable ICU 2.0
759      */
760     static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
761 
762     /**
763      * Returns a scientific format for the specified locale.
764      * @param inLocale    the given locale.
765      * @stable ICU 2.0
766      */
767     static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
768                                                 UErrorCode&);
769 
770     /**
771      * Get the set of Locales for which NumberFormats are installed.
772      * @param count    Output param to receive the size of the locales
773      * @stable ICU 2.0
774      */
775     static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
776 
777 #if !UCONFIG_NO_SERVICE
778     /**
779      * Register a new NumberFormatFactory.  The factory will be adopted.
780      * Because ICU may choose to cache NumberFormat objects internally,
781      * this must be called at application startup, prior to any calls to
782      * NumberFormat::createInstance to avoid undefined behavior.
783      * @param toAdopt the NumberFormatFactory instance to be adopted
784      * @param status the in/out status code, no special meanings are assigned
785      * @return a registry key that can be used to unregister this factory
786      * @stable ICU 2.6
787      */
788     static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
789 
790     /**
791      * Unregister a previously-registered NumberFormatFactory using the key returned from the
792      * register call.  Key becomes invalid after a successful call and should not be used again.
793      * The NumberFormatFactory corresponding to the key will be deleted.
794      * Because ICU may choose to cache NumberFormat objects internally,
795      * this should be called during application shutdown, after all calls to
796      * NumberFormat::createInstance to avoid undefined behavior.
797      * @param key the registry key returned by a previous call to registerFactory
798      * @param status the in/out status code, no special meanings are assigned
799      * @return TRUE if the factory for the key was successfully unregistered
800      * @stable ICU 2.6
801      */
802     static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
803 
804     /**
805      * Return a StringEnumeration over the locales available at the time of the call,
806      * including registered locales.
807      * @return a StringEnumeration over the locales available at the time of the call
808      * @stable ICU 2.6
809      */
810     static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
811 #endif /* UCONFIG_NO_SERVICE */
812 
813     /**
814      * Returns true if grouping is used in this format. For example,
815      * in the English locale, with grouping on, the number 1234567
816      * might be formatted as "1,234,567". The grouping separator as
817      * well as the size of each group is locale dependant and is
818      * determined by sub-classes of NumberFormat.
819      * @see setGroupingUsed
820      * @stable ICU 2.0
821      */
822     UBool isGroupingUsed(void) const;
823 
824     /**
825      * Set whether or not grouping will be used in this format.
826      * @param newValue    True, grouping will be used in this format.
827      * @see getGroupingUsed
828      * @stable ICU 2.0
829      */
830     virtual void setGroupingUsed(UBool newValue);
831 
832     /**
833      * Returns the maximum number of digits allowed in the integer portion of a
834      * number.
835      * @return     the maximum number of digits allowed in the integer portion of a
836      *             number.
837      * @see setMaximumIntegerDigits
838      * @stable ICU 2.0
839      */
840     int32_t getMaximumIntegerDigits(void) const;
841 
842     /**
843      * Sets the maximum number of digits allowed in the integer portion of a
844      * number. maximumIntegerDigits must be >= minimumIntegerDigits.  If the
845      * new value for maximumIntegerDigits is less than the current value
846      * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
847      * the new value.
848      *
849      * @param newValue    the new value for the maximum number of digits
850      *                    allowed in the integer portion of a number.
851      * @see getMaximumIntegerDigits
852      * @stable ICU 2.0
853      */
854     virtual void setMaximumIntegerDigits(int32_t newValue);
855 
856     /**
857      * Returns the minimum number of digits allowed in the integer portion of a
858      * number.
859      * @return    the minimum number of digits allowed in the integer portion of a
860      *            number.
861      * @see setMinimumIntegerDigits
862      * @stable ICU 2.0
863      */
864     int32_t getMinimumIntegerDigits(void) const;
865 
866     /**
867      * Sets the minimum number of digits allowed in the integer portion of a
868      * number. minimumIntegerDigits must be &lt;= maximumIntegerDigits.  If the
869      * new value for minimumIntegerDigits exceeds the current value
870      * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
871      * the new value.
872      * @param newValue    the new value to be set.
873      * @see getMinimumIntegerDigits
874      * @stable ICU 2.0
875      */
876     virtual void setMinimumIntegerDigits(int32_t newValue);
877 
878     /**
879      * Returns the maximum number of digits allowed in the fraction portion of a
880      * number.
881      * @return    the maximum number of digits allowed in the fraction portion of a
882      *            number.
883      * @see setMaximumFractionDigits
884      * @stable ICU 2.0
885      */
886     int32_t getMaximumFractionDigits(void) const;
887 
888     /**
889      * Sets the maximum number of digits allowed in the fraction portion of a
890      * number. maximumFractionDigits must be >= minimumFractionDigits.  If the
891      * new value for maximumFractionDigits is less than the current value
892      * of minimumFractionDigits, then minimumFractionDigits will also be set to
893      * the new value.
894      * @param newValue    the new value to be set.
895      * @see getMaximumFractionDigits
896      * @stable ICU 2.0
897      */
898     virtual void setMaximumFractionDigits(int32_t newValue);
899 
900     /**
901      * Returns the minimum number of digits allowed in the fraction portion of a
902      * number.
903      * @return    the minimum number of digits allowed in the fraction portion of a
904      *            number.
905      * @see setMinimumFractionDigits
906      * @stable ICU 2.0
907      */
908     int32_t getMinimumFractionDigits(void) const;
909 
910     /**
911      * Sets the minimum number of digits allowed in the fraction portion of a
912      * number. minimumFractionDigits must be &lt;= maximumFractionDigits.   If the
913      * new value for minimumFractionDigits exceeds the current value
914      * of maximumFractionDigits, then maximumIntegerDigits will also be set to
915      * the new value
916      * @param newValue    the new value to be set.
917      * @see getMinimumFractionDigits
918      * @stable ICU 2.0
919      */
920     virtual void setMinimumFractionDigits(int32_t newValue);
921 
922     /**
923      * Sets the currency used to display currency
924      * amounts.  This takes effect immediately, if this format is a
925      * currency format.  If this format is not a currency format, then
926      * the currency is used if and when this object becomes a
927      * currency format.
928      * @param theCurrency a 3-letter ISO code indicating new currency
929      * to use.  It need not be null-terminated.  May be the empty
930      * string or NULL to indicate no currency.
931      * @param ec input-output error code
932      * @stable ICU 3.0
933      */
934     virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec);
935 
936     /**
937      * Gets the currency used to display currency
938      * amounts.  This may be an empty string for some subclasses.
939      * @return a 3-letter null-terminated ISO code indicating
940      * the currency in use, or a pointer to the empty string.
941      * @stable ICU 2.6
942      */
943     const UChar* getCurrency() const;
944 
945     /**
946      * Set a particular UDisplayContext value in the formatter, such as
947      * UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
948      * @param value The UDisplayContext value to set.
949      * @param status Input/output status. If at entry this indicates a failure
950      *               status, the function will do nothing; otherwise this will be
951      *               updated with any new status from the function.
952      * @stable ICU 53
953      */
954     virtual void setContext(UDisplayContext value, UErrorCode& status);
955 
956     /**
957      * Get the formatter's UDisplayContext value for the specified UDisplayContextType,
958      * such as UDISPCTX_TYPE_CAPITALIZATION.
959      * @param type The UDisplayContextType whose value to return
960      * @param status Input/output status. If at entry this indicates a failure
961      *               status, the function will do nothing; otherwise this will be
962      *               updated with any new status from the function.
963      * @return The UDisplayContextValue for the specified type.
964      * @stable ICU 53
965      */
966     virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const;
967 
968 public:
969 
970     /**
971      * Return the class ID for this class.  This is useful for
972      * comparing to a return value from getDynamicClassID(). Note that,
973      * because NumberFormat is an abstract base class, no fully constructed object
974      * will have the class ID returned by NumberFormat::getStaticClassID().
975      * @return The class ID for all objects of this class.
976      * @stable ICU 2.0
977      */
978     static UClassID U_EXPORT2 getStaticClassID(void);
979 
980     /**
981      * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
982      * This method is to implement a simple version of RTTI, since not all
983      * C++ compilers support genuine RTTI.  Polymorphic operator==() and
984      * clone() methods call this method.
985      * <P>
986      * @return The class ID for this object. All objects of a
987      * given class have the same class ID.  Objects of
988      * other classes have different class IDs.
989      * @stable ICU 2.0
990      */
991     virtual UClassID getDynamicClassID(void) const = 0;
992 
993 protected:
994 
995     /**
996      * Default constructor for subclass use only.
997      * @stable ICU 2.0
998      */
999     NumberFormat();
1000 
1001     /**
1002      * Copy constructor.
1003      * @stable ICU 2.0
1004      */
1005     NumberFormat(const NumberFormat&);
1006 
1007     /**
1008      * Assignment operator.
1009      * @stable ICU 2.0
1010      */
1011     NumberFormat& operator=(const NumberFormat&);
1012 
1013     /**
1014      * Returns the currency in effect for this formatter.  Subclasses
1015      * should override this method as needed.  Unlike getCurrency(),
1016      * this method should never return "".
1017      * @result output parameter for null-terminated result, which must
1018      * have a capacity of at least 4
1019      * @internal
1020      */
1021     virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const;
1022 
1023 #ifndef U_HIDE_INTERNAL_API
1024     /**
1025      * Creates the specified number format style of the desired locale.
1026      * If mustBeDecimalFormat is TRUE, then the returned pointer is
1027      * either a DecimalFormat or it is NULL.
1028      * @internal
1029      */
1030     static NumberFormat* makeInstance(const Locale& desiredLocale,
1031                                       UNumberFormatStyle style,
1032                                       UBool mustBeDecimalFormat,
1033                                       UErrorCode& errorCode);
1034 #endif  /* U_HIDE_INTERNAL_API */
1035 
1036 private:
1037 
1038     static UBool isStyleSupported(UNumberFormatStyle style);
1039 
1040     /**
1041      * Creates the specified decimal format style of the desired locale.
1042      * @param desiredLocale    the given locale.
1043      * @param style            the given style.
1044      * @param errorCode        Output param filled with success/failure status.
1045      * @return                 A new NumberFormat instance.
1046      */
1047     static NumberFormat* makeInstance(const Locale& desiredLocale,
1048                                       UNumberFormatStyle style,
1049                                       UErrorCode& errorCode);
1050 
1051     UBool       fGroupingUsed;
1052     int32_t     fMaxIntegerDigits;
1053     int32_t     fMinIntegerDigits;
1054     int32_t     fMaxFractionDigits;
1055     int32_t     fMinFractionDigits;
1056 
1057   protected:
1058     /** \internal */
1059     static const int32_t gDefaultMaxIntegerDigits;
1060     /** \internal */
1061     static const int32_t gDefaultMinIntegerDigits;
1062 
1063   private:
1064     UBool      fParseIntegerOnly;
1065     UBool      fLenient; // TRUE => lenient parse is enabled
1066 
1067     // ISO currency code
1068     UChar      fCurrency[4];
1069 
1070     UDisplayContext fCapitalizationContext;
1071 
1072     friend class ICUNumberFormatFactory; // access to makeInstance
1073     friend class ICUNumberFormatService;
1074     friend class ::NumberFormatTest;  // access to isStyleSupported()
1075 };
1076 
1077 #if !UCONFIG_NO_SERVICE
1078 /**
1079  * A NumberFormatFactory is used to register new number formats.  The factory
1080  * should be able to create any of the predefined formats for each locale it
1081  * supports.  When registered, the locales it supports extend or override the
1082  * locale already supported by ICU.
1083  *
1084  * @stable ICU 2.6
1085  */
1086 class U_I18N_API NumberFormatFactory : public UObject {
1087 public:
1088 
1089     /**
1090      * Destructor
1091      * @stable ICU 3.0
1092      */
1093     virtual ~NumberFormatFactory();
1094 
1095     /**
1096      * Return true if this factory will be visible.  Default is true.
1097      * If not visible, the locales supported by this factory will not
1098      * be listed by getAvailableLocales.
1099      * @stable ICU 2.6
1100      */
1101     virtual UBool visible(void) const = 0;
1102 
1103     /**
1104      * Return the locale names directly supported by this factory.  The number of names
1105      * is returned in count;
1106      * @stable ICU 2.6
1107      */
1108     virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0;
1109 
1110     /**
1111      * Return a number format of the appropriate type.  If the locale
1112      * is not supported, return null.  If the locale is supported, but
1113      * the type is not provided by this service, return null.  Otherwise
1114      * return an appropriate instance of NumberFormat.
1115      * @stable ICU 2.6
1116      */
1117     virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0;
1118 };
1119 
1120 /**
1121  * A NumberFormatFactory that supports a single locale.  It can be visible or invisible.
1122  * @stable ICU 2.6
1123  */
1124 class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory {
1125 protected:
1126     /**
1127      * True if the locale supported by this factory is visible.
1128      * @stable ICU 2.6
1129      */
1130     const UBool _visible;
1131 
1132     /**
1133      * The locale supported by this factory, as a UnicodeString.
1134      * @stable ICU 2.6
1135      */
1136     UnicodeString _id;
1137 
1138 public:
1139     /**
1140      * @stable ICU 2.6
1141      */
1142     SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE);
1143 
1144     /**
1145      * @stable ICU 3.0
1146      */
1147     virtual ~SimpleNumberFormatFactory();
1148 
1149     /**
1150      * @stable ICU 2.6
1151      */
1152     virtual UBool visible(void) const;
1153 
1154     /**
1155      * @stable ICU 2.6
1156      */
1157     virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const;
1158 };
1159 #endif /* #if !UCONFIG_NO_SERVICE */
1160 
1161 // -------------------------------------
1162 
1163 inline UBool
isParseIntegerOnly()1164 NumberFormat::isParseIntegerOnly() const
1165 {
1166     return fParseIntegerOnly;
1167 }
1168 
1169 inline UBool
isLenient()1170 NumberFormat::isLenient() const
1171 {
1172     return fLenient;
1173 }
1174 
1175 U_NAMESPACE_END
1176 
1177 #endif /* #if !UCONFIG_NO_FORMATTING */
1178 
1179 #endif // _NUMFMT
1180 //eof
1181