1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ********************************************************************************
5 * Copyright (C) 1997-2016, International Business Machines Corporation and others.
7 ********************************************************************************
11 * Modification History:
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 ********************************************************************************
27 #include "unicode/utypes.h"
29 #if U_SHOW_CPLUSPLUS_API
33 * \brief C++ API: Compatibility APIs for number formatting.
36 #if !UCONFIG_NO_FORMATTING
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"
46 class NumberFormatTest
;
50 class SharedNumberFormat
;
52 #if !UCONFIG_NO_SERVICE
53 class NumberFormatFactory
;
54 class StringEnumeration
;
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.
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
67 * \headerfile unicode/numfmt.h "unicode/numfmt.h"
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.
74 * To format a number for the current Locale, use one of the static
78 * #include "unicode/numfmt.h"
79 * #include "unicode/unistr.h"
80 * #include "unicode/ustream.h"
81 * using namespace std;
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;
92 * Note that there are additional factory methods within subclasses of
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.
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);
107 * cout << " Example 2: " << myString << endl;
109 * To format a number for a different Locale, specify it in the
110 * call to \c createInstance().
112 * nf = NumberFormat::createInstance(Locale::getFrench(), success);
114 * You can use a \c NumberFormat to parse also.
116 * UErrorCode success;
117 * Formattable result(-999); // initialized with error code
118 * nf->parse(myString, result, success);
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%.
126 * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance().
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".
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.
147 * You can also use forms of the parse and format methods with
148 * \c ParsePosition and \c FieldPosition to allow you to:
150 * <li>(a) progressively parse through pieces of a string.
151 * <li>(b) align the decimal point and other areas.
153 * For example, you can align numbers in two ways.
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
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.
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.
175 class U_I18N_API NumberFormat
: public Format
{
181 * For more detail on rounding modes, see:
182 * http://userguide.icu-project.org/formatparse/numbers/rounding-modes
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 */
198 * Return U_FORMAT_INEXACT_ERROR if number does not format exactly.
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.
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.
213 * These constants are provided for backwards compatibility only.
214 * Please use the C style constants defined in the header file unum.h.
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 #ifndef U_HIDE_DRAFT_API
244 kMeasureUnitField
= UNUM_MEASURE_UNIT_FIELD
,
246 kCompactField
= UNUM_COMPACT_FIELD
,
247 #endif // U_HIDE_DRAFT_API
250 * These constants are provided for backwards compatibility only.
251 * Please use the constants defined in the header file unum.h.
253 /** @stable ICU 2.0 */
254 INTEGER_FIELD
= UNUM_INTEGER_FIELD
,
255 /** @stable ICU 2.0 */
256 FRACTION_FIELD
= UNUM_FRACTION_FIELD
263 virtual ~NumberFormat();
266 * Clones this object polymorphically.
267 * The caller owns the result and should delete it when done.
268 * @return clone, or nullptr if an error occurred
271 virtual NumberFormat
* clone() const = 0;
274 * Return true if the given Format objects are semantically equal.
275 * Objects of different subclasses are considered unequal.
276 * @return true if the given Format objects are semantically equal.
279 virtual UBool
operator==(const Format
& other
) const;
282 using Format::format
;
285 * Format an object to produce a string. This method handles
286 * Formattable objects with numeric types. If the Formattable
287 * object type is not a numeric type, then it returns a failing
290 * @param obj The object to format.
291 * @param appendTo Output parameter to receive result.
292 * Result is appended to existing contents.
293 * @param pos On input: an alignment field, if desired.
294 * On output: the offsets of the alignment field.
295 * @param status Output param filled with success/failure status.
296 * @return Reference to 'appendTo' parameter.
299 virtual UnicodeString
& format(const Formattable
& obj
,
300 UnicodeString
& appendTo
,
302 UErrorCode
& status
) const;
305 * Format an object to produce a string. This method handles
306 * Formattable objects with numeric types. If the Formattable
307 * object type is not a numeric type, then it returns a failing
310 * @param obj The object to format.
311 * @param appendTo Output parameter to receive result.
312 * Result is appended to existing contents.
313 * @param posIter On return, can be used to iterate over positions
314 * of fields generated by this format call. Can be
316 * @param status Output param filled with success/failure status.
317 * @return Reference to 'appendTo' parameter.
320 virtual UnicodeString
& format(const Formattable
& obj
,
321 UnicodeString
& appendTo
,
322 FieldPositionIterator
* posIter
,
323 UErrorCode
& status
) const;
326 * Parse a string to produce an object. This methods handles
327 * parsing of numeric strings into Formattable objects with numeric
330 * Before calling, set parse_pos.index to the offset you want to
331 * start parsing at in the source. After calling, parse_pos.index
332 * indicates the position after the successfully parsed text. If
333 * an error occurs, parse_pos.index is unchanged.
335 * When parsing, leading whitespace is discarded (with successful
336 * parse), while trailing whitespace is left as is.
338 * See Format::parseObject() for more.
340 * @param source The string to be parsed into an object.
341 * @param result Formattable to be set to the parse result.
342 * If parse fails, return contents are undefined.
343 * @param parse_pos The position to start parsing at. Upon return
344 * this param is set to the position after the
345 * last character successfully parsed. If the
346 * source is not parsed successfully, this param
347 * will remain unchanged.
348 * @return A newly created Formattable* object, or NULL
349 * on failure. The caller owns this and should
350 * delete it when done.
353 virtual void parseObject(const UnicodeString
& source
,
355 ParsePosition
& parse_pos
) const;
358 * Format a double number. These methods call the NumberFormat
359 * pure virtual format() methods with the default FieldPosition.
361 * @param number The value to be formatted.
362 * @param appendTo Output parameter to receive result.
363 * Result is appended to existing contents.
364 * @return Reference to 'appendTo' parameter.
367 UnicodeString
& format( double number
,
368 UnicodeString
& appendTo
) const;
371 * Format a long number. These methods call the NumberFormat
372 * pure virtual format() methods with the default FieldPosition.
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.
380 UnicodeString
& format( int32_t number
,
381 UnicodeString
& appendTo
) const;
384 * Format an int64 number. These methods call the NumberFormat
385 * pure virtual format() methods with the default FieldPosition.
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.
393 UnicodeString
& format( int64_t number
,
394 UnicodeString
& appendTo
) const;
397 * Format a double number. Concrete subclasses must implement
398 * these pure virtual methods.
400 * @param number The value to be formatted.
401 * @param appendTo Output parameter to receive result.
402 * Result is appended to existing contents.
403 * @param pos On input: an alignment field, if desired.
404 * On output: the offsets of the alignment field.
405 * @return Reference to 'appendTo' parameter.
408 virtual UnicodeString
& format(double number
,
409 UnicodeString
& appendTo
,
410 FieldPosition
& pos
) const = 0;
412 * Format a double number. By default, the parent function simply
413 * calls the base class and does not return an error status.
414 * Therefore, the status may be ignored in some subclasses.
416 * @param number The value to be formatted.
417 * @param appendTo Output parameter to receive result.
418 * Result is appended to existing contents.
419 * @param pos On input: an alignment field, if desired.
420 * On output: the offsets of the alignment field.
421 * @param status error status
422 * @return Reference to 'appendTo' parameter.
425 virtual UnicodeString
& format(double number
,
426 UnicodeString
& appendTo
,
428 UErrorCode
&status
) const;
430 * Format a double number. Subclasses must implement
433 * @param number The value to be formatted.
434 * @param appendTo Output parameter to receive result.
435 * Result is appended to existing contents.
436 * @param posIter On return, can be used to iterate over positions
437 * of fields generated by this format call.
439 * @param status Output param filled with success/failure status.
440 * @return Reference to 'appendTo' parameter.
443 virtual UnicodeString
& format(double number
,
444 UnicodeString
& appendTo
,
445 FieldPositionIterator
* posIter
,
446 UErrorCode
& status
) const;
448 * Format a long number. Concrete subclasses must implement
449 * these pure virtual methods.
451 * @param number The value to be formatted.
452 * @param appendTo Output parameter to receive result.
453 * Result is appended to existing contents.
454 * @param pos On input: an alignment field, if desired.
455 * On output: the offsets of the alignment field.
456 * @return Reference to 'appendTo' parameter.
459 virtual UnicodeString
& format(int32_t number
,
460 UnicodeString
& appendTo
,
461 FieldPosition
& pos
) const = 0;
464 * Format a long number. Concrete subclasses may override
465 * this function to provide status return.
467 * @param number The value to be formatted.
468 * @param appendTo Output parameter to receive result.
469 * Result is appended to existing contents.
470 * @param pos On input: an alignment field, if desired.
471 * On output: the offsets of the alignment field.
472 * @param status the output status.
473 * @return Reference to 'appendTo' parameter.
476 virtual UnicodeString
& format(int32_t number
,
477 UnicodeString
& appendTo
,
479 UErrorCode
&status
) const;
482 * Format an int32 number. Subclasses must implement
485 * @param number The value to be formatted.
486 * @param appendTo Output parameter to receive result.
487 * Result is appended to existing contents.
488 * @param posIter On return, can be used to iterate over positions
489 * of fields generated by this format call.
491 * @param status Output param filled with success/failure status.
492 * @return Reference to 'appendTo' parameter.
495 virtual UnicodeString
& format(int32_t number
,
496 UnicodeString
& appendTo
,
497 FieldPositionIterator
* posIter
,
498 UErrorCode
& status
) const;
500 * Format an int64 number. (Not abstract to retain compatibility
501 * with earlier releases, however subclasses should override this
502 * method as it just delegates to format(int32_t number...);
504 * @param number The value to be formatted.
505 * @param appendTo Output parameter to receive result.
506 * Result is appended to existing contents.
507 * @param pos On input: an alignment field, if desired.
508 * On output: the offsets of the alignment field.
509 * @return Reference to 'appendTo' parameter.
512 virtual UnicodeString
& format(int64_t number
,
513 UnicodeString
& appendTo
,
514 FieldPosition
& pos
) const;
517 * Format an int64 number. (Not abstract to retain compatibility
518 * with earlier releases, however subclasses should override this
519 * method as it just delegates to format(int32_t number...);
521 * @param number The value to be formatted.
522 * @param appendTo Output parameter to receive result.
523 * Result is appended to existing contents.
524 * @param pos On input: an alignment field, if desired.
525 * On output: the offsets of the alignment field.
526 * @param status Output param filled with success/failure status.
527 * @return Reference to 'appendTo' parameter.
530 virtual UnicodeString
& format(int64_t number
,
531 UnicodeString
& appendTo
,
533 UErrorCode
& status
) const;
535 * Format an int64 number. Subclasses must implement
538 * @param number The value to be formatted.
539 * @param appendTo Output parameter to receive result.
540 * Result is appended to existing contents.
541 * @param posIter On return, can be used to iterate over positions
542 * of fields generated by this format call.
544 * @param status Output param filled with success/failure status.
545 * @return Reference to 'appendTo' parameter.
548 virtual UnicodeString
& format(int64_t number
,
549 UnicodeString
& appendTo
,
550 FieldPositionIterator
* posIter
,
551 UErrorCode
& status
) const;
554 * Format a decimal number. Subclasses must implement
555 * this method. The syntax of the unformatted number is a "numeric string"
556 * as defined in the Decimal Arithmetic Specification, available at
557 * http://speleotrove.com/decimal
559 * @param number The unformatted number, as a string, to be formatted.
560 * @param appendTo Output parameter to receive result.
561 * Result is appended to existing contents.
562 * @param posIter On return, can be used to iterate over positions
563 * of fields generated by this format call.
565 * @param status Output param filled with success/failure status.
566 * @return Reference to 'appendTo' parameter.
569 virtual UnicodeString
& format(StringPiece number
,
570 UnicodeString
& appendTo
,
571 FieldPositionIterator
* posIter
,
572 UErrorCode
& status
) const;
574 // Can't use #ifndef U_HIDE_INTERNAL_API because these are virtual methods
577 * Format a decimal number.
578 * The number is a DecimalQuantity wrapper onto a floating point decimal number.
579 * The default implementation in NumberFormat converts the decimal number
580 * to a double and formats that. Subclasses of NumberFormat that want
581 * to specifically handle big decimal numbers must override this method.
582 * class DecimalFormat does so.
584 * @param number The number, a DecimalQuantity format Decimal Floating Point.
585 * @param appendTo Output parameter to receive result.
586 * Result is appended to existing contents.
587 * @param posIter On return, can be used to iterate over positions
588 * of fields generated by this format call.
589 * @param status Output param filled with success/failure status.
590 * @return Reference to 'appendTo' parameter.
593 virtual UnicodeString
& format(const number::impl::DecimalQuantity
&number
,
594 UnicodeString
& appendTo
,
595 FieldPositionIterator
* posIter
,
596 UErrorCode
& status
) const;
599 * Format a decimal number.
600 * The number is a DecimalQuantity wrapper onto a floating point decimal number.
601 * The default implementation in NumberFormat converts the decimal number
602 * to a double and formats that. Subclasses of NumberFormat that want
603 * to specifically handle big decimal numbers must override this method.
604 * class DecimalFormat does so.
606 * @param number The number, a DecimalQuantity format Decimal Floating Point.
607 * @param appendTo Output parameter to receive result.
608 * Result is appended to existing contents.
609 * @param pos On input: an alignment field, if desired.
610 * On output: the offsets of the alignment field.
611 * @param status Output param filled with success/failure status.
612 * @return Reference to 'appendTo' parameter.
615 virtual UnicodeString
& format(const number::impl::DecimalQuantity
&number
,
616 UnicodeString
& appendTo
,
618 UErrorCode
& status
) const;
621 * Return a long if possible (e.g. within range LONG_MAX,
622 * LONG_MAX], and with no decimals), otherwise a double. If
623 * IntegerOnly is set, will stop at a decimal point (or equivalent;
624 * e.g. for rational numbers "1 2/3", will stop after the 1).
626 * If no object can be parsed, index is unchanged, and NULL is
629 * This is a pure virtual which concrete subclasses must implement.
631 * @param text The text to be parsed.
632 * @param result Formattable to be set to the parse result.
633 * If parse fails, return contents are undefined.
634 * @param parsePosition The position to start parsing at on input.
635 * On output, moved to after the last successfully
636 * parse character. On parse failure, does not change.
639 virtual void parse(const UnicodeString
& text
,
641 ParsePosition
& parsePosition
) const = 0;
644 * Parse a string as a numeric value, and return a Formattable
645 * numeric object. This method parses integers only if IntegerOnly
648 * @param text The text to be parsed.
649 * @param result Formattable to be set to the parse result.
650 * If parse fails, return contents are undefined.
651 * @param status Output parameter set to a failure error code
652 * when a failure occurs. The error code when the
653 * string fails to parse is U_INVALID_FORMAT_ERROR,
654 * unless overridden by a subclass.
655 * @see NumberFormat::isParseIntegerOnly
658 virtual void parse(const UnicodeString
& text
,
660 UErrorCode
& status
) const;
663 * Parses text from the given string as a currency amount. Unlike
664 * the parse() method, this method will attempt to parse a generic
665 * currency name, searching for a match of this object's locale's
666 * currency display names, or for a 3-letter ISO currency code.
667 * This method will fail if this format is not a currency format,
668 * that is, if it does not contain the currency pattern symbol
669 * (U+00A4) in its prefix or suffix.
671 * @param text the string to parse
672 * @param pos input-output position; on input, the position within text
673 * to match; must have 0 <= pos.getIndex() < text.length();
674 * on output, the position after the last matched character.
675 * If the parse fails, the position in unchanged upon output.
676 * @return if parse succeeds, a pointer to a newly-created CurrencyAmount
677 * object (owned by the caller) containing information about
678 * the parsed currency; if parse fails, this is NULL.
681 virtual CurrencyAmount
* parseCurrency(const UnicodeString
& text
,
682 ParsePosition
& pos
) const;
685 * Return true if this format will parse numbers as integers
686 * only. For example in the English locale, with ParseIntegerOnly
687 * true, the string "1234." would be parsed as the integer value
688 * 1234 and parsing would stop at the "." character. Of course,
689 * the exact format accepted by the parse operation is locale
690 * dependant and determined by sub-classes of NumberFormat.
691 * @return true if this format will parse numbers as integers
695 UBool
isParseIntegerOnly(void) const;
698 * Sets whether or not numbers should be parsed as integers only.
699 * @param value set True, this format will parse numbers as integers
701 * @see isParseIntegerOnly
704 virtual void setParseIntegerOnly(UBool value
);
707 * Sets whether lenient parsing should be enabled (it is off by default).
709 * @param enable \c TRUE if lenient parsing should be used,
710 * \c FALSE otherwise.
713 virtual void setLenient(UBool enable
);
716 * Returns whether lenient parsing is enabled (it is off by default).
718 * @return \c TRUE if lenient parsing is enabled,
719 * \c FALSE otherwise.
723 virtual UBool
isLenient(void) const;
726 * Create a default style NumberFormat for the current default locale.
727 * The default formatting style is locale dependent.
729 * <strong>NOTE:</strong> New users are strongly encouraged to use
730 * {@link icu::number::NumberFormatter} instead of NumberFormat.
733 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
736 * Create a default style NumberFormat for the specified locale.
737 * The default formatting style is locale dependent.
738 * @param inLocale the given locale.
740 * <strong>NOTE:</strong> New users are strongly encouraged to use
741 * {@link icu::number::NumberFormatter} instead of NumberFormat.
744 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& inLocale
,
748 * Create a specific style NumberFormat for the specified locale.
750 * <strong>NOTE:</strong> New users are strongly encouraged to use
751 * {@link icu::number::NumberFormatter} instead of NumberFormat.
752 * @param desiredLocale the given locale.
753 * @param style the given style.
754 * @param errorCode Output param filled with success/failure status.
755 * @return A new NumberFormat instance.
758 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
,
759 UNumberFormatStyle style
,
760 UErrorCode
& errorCode
);
762 #ifndef U_HIDE_INTERNAL_API
766 * Creates NumberFormat instance without using the cache.
769 static NumberFormat
* internalCreateInstance(
770 const Locale
& desiredLocale
,
771 UNumberFormatStyle style
,
772 UErrorCode
& errorCode
);
776 * Returns handle to the shared, cached NumberFormat instance for given
777 * locale. On success, caller must call removeRef() on returned value
778 * once it is done with the shared instance.
781 static const SharedNumberFormat
* U_EXPORT2
createSharedInstance(
782 const Locale
& inLocale
, UNumberFormatStyle style
, UErrorCode
& status
);
784 #endif /* U_HIDE_INTERNAL_API */
787 * Returns a currency format for the current default locale.
789 * <strong>NOTE:</strong> New users are strongly encouraged to use
790 * {@link icu::number::NumberFormatter} instead of NumberFormat.
793 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
796 * Returns a currency format for the specified locale.
798 * <strong>NOTE:</strong> New users are strongly encouraged to use
799 * {@link icu::number::NumberFormatter} instead of NumberFormat.
800 * @param inLocale the given locale.
803 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
807 * Returns a percentage format for the current default locale.
809 * <strong>NOTE:</strong> New users are strongly encouraged to use
810 * {@link icu::number::NumberFormatter} instead of NumberFormat.
813 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
816 * Returns a percentage format for the specified locale.
818 * <strong>NOTE:</strong> New users are strongly encouraged to use
819 * {@link icu::number::NumberFormatter} instead of NumberFormat.
820 * @param inLocale the given locale.
823 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
827 * Returns a scientific format for the current default locale.
829 * <strong>NOTE:</strong> New users are strongly encouraged to use
830 * {@link icu::number::NumberFormatter} instead of NumberFormat.
833 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
836 * Returns a scientific format for the specified locale.
838 * <strong>NOTE:</strong> New users are strongly encouraged to use
839 * {@link icu::number::NumberFormatter} instead of NumberFormat.
840 * @param inLocale the given locale.
843 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
847 * Get the set of Locales for which NumberFormats are installed.
848 * @param count Output param to receive the size of the locales
851 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
853 #if !UCONFIG_NO_SERVICE
855 * Register a new NumberFormatFactory. The factory will be adopted.
856 * Because ICU may choose to cache NumberFormat objects internally,
857 * this must be called at application startup, prior to any calls to
858 * NumberFormat::createInstance to avoid undefined behavior.
859 * @param toAdopt the NumberFormatFactory instance to be adopted
860 * @param status the in/out status code, no special meanings are assigned
861 * @return a registry key that can be used to unregister this factory
864 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
867 * Unregister a previously-registered NumberFormatFactory using the key returned from the
868 * register call. Key becomes invalid after a successful call and should not be used again.
869 * The NumberFormatFactory corresponding to the key will be deleted.
870 * Because ICU may choose to cache NumberFormat objects internally,
871 * this should be called during application shutdown, after all calls to
872 * NumberFormat::createInstance to avoid undefined behavior.
873 * @param key the registry key returned by a previous call to registerFactory
874 * @param status the in/out status code, no special meanings are assigned
875 * @return TRUE if the factory for the key was successfully unregistered
878 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
881 * Return a StringEnumeration over the locales available at the time of the call,
882 * including registered locales.
883 * @return a StringEnumeration over the locales available at the time of the call
886 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
887 #endif /* UCONFIG_NO_SERVICE */
890 * Returns true if grouping is used in this format. For example,
891 * in the English locale, with grouping on, the number 1234567
892 * might be formatted as "1,234,567". The grouping separator as
893 * well as the size of each group is locale dependent and is
894 * determined by sub-classes of NumberFormat.
895 * @see setGroupingUsed
898 UBool
isGroupingUsed(void) const;
901 * Set whether or not grouping will be used in this format.
902 * @param newValue True, grouping will be used in this format.
903 * @see getGroupingUsed
906 virtual void setGroupingUsed(UBool newValue
);
909 * Returns the maximum number of digits allowed in the integer portion of a
911 * @return the maximum number of digits allowed in the integer portion of a
913 * @see setMaximumIntegerDigits
916 int32_t getMaximumIntegerDigits(void) const;
919 * Sets the maximum number of digits allowed in the integer portion of a
920 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
921 * new value for maximumIntegerDigits is less than the current value
922 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
925 * @param newValue the new value for the maximum number of digits
926 * allowed in the integer portion of a number.
927 * @see getMaximumIntegerDigits
930 virtual void setMaximumIntegerDigits(int32_t newValue
);
933 * Returns the minimum number of digits allowed in the integer portion of a
935 * @return the minimum number of digits allowed in the integer portion of a
937 * @see setMinimumIntegerDigits
940 int32_t getMinimumIntegerDigits(void) const;
943 * Sets the minimum number of digits allowed in the integer portion of a
944 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
945 * new value for minimumIntegerDigits exceeds the current value
946 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
948 * @param newValue the new value to be set.
949 * @see getMinimumIntegerDigits
952 virtual void setMinimumIntegerDigits(int32_t newValue
);
955 * Returns the maximum number of digits allowed in the fraction portion of a
957 * @return the maximum number of digits allowed in the fraction portion of a
959 * @see setMaximumFractionDigits
962 int32_t getMaximumFractionDigits(void) const;
965 * Sets the maximum number of digits allowed in the fraction portion of a
966 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
967 * new value for maximumFractionDigits is less than the current value
968 * of minimumFractionDigits, then minimumFractionDigits will also be set to
970 * @param newValue the new value to be set.
971 * @see getMaximumFractionDigits
974 virtual void setMaximumFractionDigits(int32_t newValue
);
977 * Returns the minimum number of digits allowed in the fraction portion of a
979 * @return the minimum number of digits allowed in the fraction portion of a
981 * @see setMinimumFractionDigits
984 int32_t getMinimumFractionDigits(void) const;
987 * Sets the minimum number of digits allowed in the fraction portion of a
988 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
989 * new value for minimumFractionDigits exceeds the current value
990 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
992 * @param newValue the new value to be set.
993 * @see getMinimumFractionDigits
996 virtual void setMinimumFractionDigits(int32_t newValue
);
999 * Sets the currency used to display currency
1000 * amounts. This takes effect immediately, if this format is a
1001 * currency format. If this format is not a currency format, then
1002 * the currency is used if and when this object becomes a
1004 * @param theCurrency a 3-letter ISO code indicating new currency
1005 * to use. It need not be null-terminated. May be the empty
1006 * string or NULL to indicate no currency.
1007 * @param ec input-output error code
1010 virtual void setCurrency(const char16_t* theCurrency
, UErrorCode
& ec
);
1013 * Gets the currency used to display currency
1014 * amounts. This may be an empty string for some subclasses.
1015 * @return a 3-letter null-terminated ISO code indicating
1016 * the currency in use, or a pointer to the empty string.
1019 const char16_t* getCurrency() const;
1022 * Set a particular UDisplayContext value in the formatter, such as
1023 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
1024 * @param value The UDisplayContext value to set.
1025 * @param status Input/output status. If at entry this indicates a failure
1026 * status, the function will do nothing; otherwise this will be
1027 * updated with any new status from the function.
1030 virtual void setContext(UDisplayContext value
, UErrorCode
& status
);
1033 * Get the formatter's UDisplayContext value for the specified UDisplayContextType,
1034 * such as UDISPCTX_TYPE_CAPITALIZATION.
1035 * @param type The UDisplayContextType whose value to return
1036 * @param status Input/output status. If at entry this indicates a failure
1037 * status, the function will do nothing; otherwise this will be
1038 * updated with any new status from the function.
1039 * @return The UDisplayContextValue for the specified type.
1042 virtual UDisplayContext
getContext(UDisplayContextType type
, UErrorCode
& status
) const;
1045 * Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary
1046 * if the subclass does not support rounding.
1047 * @return A rounding mode
1050 virtual ERoundingMode
getRoundingMode(void) const;
1053 * Set the rounding mode. If a subclass does not support rounding, this will do nothing.
1054 * @param roundingMode A rounding mode
1057 virtual void setRoundingMode(ERoundingMode roundingMode
);
1060 * Group-set several settings used for numbers in date formats.
1062 * setGroupingUsed(FALSE);
1063 * setParseIntegerOnly(TRUE);
1064 * setMinimumFractionDigits(0);
1067 virtual void setDateSettings(void);
1072 * Return the class ID for this class. This is useful for
1073 * comparing to a return value from getDynamicClassID(). Note that,
1074 * because NumberFormat is an abstract base class, no fully constructed object
1075 * will have the class ID returned by NumberFormat::getStaticClassID().
1076 * @return The class ID for all objects of this class.
1079 static UClassID U_EXPORT2
getStaticClassID(void);
1082 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
1083 * This method is to implement a simple version of RTTI, since not all
1084 * C++ compilers support genuine RTTI. Polymorphic operator==() and
1085 * clone() methods call this method.
1087 * @return The class ID for this object. All objects of a
1088 * given class have the same class ID. Objects of
1089 * other classes have different class IDs.
1092 virtual UClassID
getDynamicClassID(void) const = 0;
1097 * Default constructor for subclass use only.
1106 NumberFormat(const NumberFormat
&);
1109 * Assignment operator.
1112 NumberFormat
& operator=(const NumberFormat
&);
1115 * Returns the currency in effect for this formatter. Subclasses
1116 * should override this method as needed. Unlike getCurrency(),
1117 * this method should never return "".
1118 * @result output parameter for null-terminated result, which must
1119 * have a capacity of at least 4
1122 virtual void getEffectiveCurrency(char16_t* result
, UErrorCode
& ec
) const;
1124 #ifndef U_HIDE_INTERNAL_API
1126 * Creates the specified number format style of the desired locale.
1127 * If mustBeDecimalFormat is TRUE, then the returned pointer is
1128 * either a DecimalFormat or it is NULL.
1131 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1132 UNumberFormatStyle style
,
1133 UBool mustBeDecimalFormat
,
1134 UErrorCode
& errorCode
);
1135 #endif /* U_HIDE_INTERNAL_API */
1139 static UBool
isStyleSupported(UNumberFormatStyle style
);
1142 * Creates the specified decimal format style of the desired locale.
1143 * @param desiredLocale the given locale.
1144 * @param style the given style.
1145 * @param errorCode Output param filled with success/failure status.
1146 * @return A new NumberFormat instance.
1148 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1149 UNumberFormatStyle style
,
1150 UErrorCode
& errorCode
);
1152 UBool fGroupingUsed
;
1153 int32_t fMaxIntegerDigits
;
1154 int32_t fMinIntegerDigits
;
1155 int32_t fMaxFractionDigits
;
1156 int32_t fMinFractionDigits
;
1160 static const int32_t gDefaultMaxIntegerDigits
;
1162 static const int32_t gDefaultMinIntegerDigits
;
1165 UBool fParseIntegerOnly
;
1166 UBool fLenient
; // TRUE => lenient parse is enabled
1168 // ISO currency code
1169 char16_t fCurrency
[4];
1171 UDisplayContext fCapitalizationContext
;
1173 friend class ICUNumberFormatFactory
; // access to makeInstance
1174 friend class ICUNumberFormatService
;
1175 friend class ::NumberFormatTest
; // access to isStyleSupported()
1178 #if !UCONFIG_NO_SERVICE
1180 * A NumberFormatFactory is used to register new number formats. The factory
1181 * should be able to create any of the predefined formats for each locale it
1182 * supports. When registered, the locales it supports extend or override the
1183 * locale already supported by ICU.
1187 class U_I18N_API NumberFormatFactory
: public UObject
{
1194 virtual ~NumberFormatFactory();
1197 * Return true if this factory will be visible. Default is true.
1198 * If not visible, the locales supported by this factory will not
1199 * be listed by getAvailableLocales.
1202 virtual UBool
visible(void) const = 0;
1205 * Return the locale names directly supported by this factory. The number of names
1206 * is returned in count;
1209 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
1212 * Return a number format of the appropriate type. If the locale
1213 * is not supported, return null. If the locale is supported, but
1214 * the type is not provided by this service, return null. Otherwise
1215 * return an appropriate instance of NumberFormat.
1218 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
1222 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
1225 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
1228 * True if the locale supported by this factory is visible.
1231 const UBool _visible
;
1234 * The locale supported by this factory, as a UnicodeString.
1243 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
1248 virtual ~SimpleNumberFormatFactory();
1253 virtual UBool
visible(void) const;
1258 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
1260 #endif /* #if !UCONFIG_NO_SERVICE */
1262 // -------------------------------------
1265 NumberFormat::isParseIntegerOnly() const
1267 return fParseIntegerOnly
;
1271 NumberFormat::isLenient() const
1278 #endif /* #if !UCONFIG_NO_FORMATTING */
1280 #endif /* U_SHOW_CPLUSPLUS_API */