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