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