Team Ai
Datasetpublic

codekingpro/portable-devtools

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

Showing the first 1,200 of 1272 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai