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"
31 * \brief C++ API: Compatibility APIs for number formatting.
34 #if !UCONFIG_NO_FORMATTING
36 #include "unicode/unistr.h"
37 #include "unicode/format.h"
38 #include "unicode/unum.h" // UNumberFormatStyle
39 #include "unicode/locid.h"
40 #include "unicode/stringpiece.h"
41 #include "unicode/curramt.h"
42 #include "unicode/udisplaycontext.h"
44 class NumberFormatTest
;
46 #if U_SHOW_CPLUSPLUS_API
49 class SharedNumberFormat
;
51 #if !UCONFIG_NO_SERVICE
52 class NumberFormatFactory
;
53 class StringEnumeration
;
57 * <p><strong>IMPORTANT:</strong> New users are strongly encouraged to see if
58 * numberformatter.h fits their use case. Although not deprecated, this header
59 * 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
,
244 * These constants are provided for backwards compatibility only.
245 * Please use the constants defined in the header file unum.h.
247 /** @stable ICU 2.0 */
248 INTEGER_FIELD
= UNUM_INTEGER_FIELD
,
249 /** @stable ICU 2.0 */
250 FRACTION_FIELD
= UNUM_FRACTION_FIELD
257 virtual ~NumberFormat();
260 * Return true if the given Format objects are semantically equal.
261 * Objects of different subclasses are considered unequal.
262 * @return true if the given Format objects are semantically equal.
265 virtual UBool
operator==(const Format
& other
) const;
268 using Format::format
;
271 * Format an object to produce a string. This method handles
272 * Formattable objects with numeric types. If the Formattable
273 * object type is not a numeric type, then it returns a failing
276 * @param obj The object to format.
277 * @param appendTo Output parameter to receive result.
278 * Result is appended to existing contents.
279 * @param pos On input: an alignment field, if desired.
280 * On output: the offsets of the alignment field.
281 * @param status Output param filled with success/failure status.
282 * @return Reference to 'appendTo' parameter.
285 virtual UnicodeString
& format(const Formattable
& obj
,
286 UnicodeString
& appendTo
,
288 UErrorCode
& status
) const;
291 * Format an object to produce a string. This method handles
292 * Formattable objects with numeric types. If the Formattable
293 * object type is not a numeric type, then it returns a failing
296 * @param obj The object to format.
297 * @param appendTo Output parameter to receive result.
298 * Result is appended to existing contents.
299 * @param posIter On return, can be used to iterate over positions
300 * of fields generated by this format call. Can be
302 * @param status Output param filled with success/failure status.
303 * @return Reference to 'appendTo' parameter.
306 virtual UnicodeString
& format(const Formattable
& obj
,
307 UnicodeString
& appendTo
,
308 FieldPositionIterator
* posIter
,
309 UErrorCode
& status
) const;
312 * Parse a string to produce an object. This methods handles
313 * parsing of numeric strings into Formattable objects with numeric
316 * Before calling, set parse_pos.index to the offset you want to
317 * start parsing at in the source. After calling, parse_pos.index
318 * indicates the position after the successfully parsed text. If
319 * an error occurs, parse_pos.index is unchanged.
321 * When parsing, leading whitespace is discarded (with successful
322 * parse), while trailing whitespace is left as is.
324 * See Format::parseObject() for more.
326 * @param source The string to be parsed into an object.
327 * @param result Formattable to be set to the parse result.
328 * If parse fails, return contents are undefined.
329 * @param parse_pos The position to start parsing at. Upon return
330 * this param is set to the position after the
331 * last character successfully parsed. If the
332 * source is not parsed successfully, this param
333 * will remain unchanged.
334 * @return A newly created Formattable* object, or NULL
335 * on failure. The caller owns this and should
336 * delete it when done.
339 virtual void parseObject(const UnicodeString
& source
,
341 ParsePosition
& parse_pos
) const;
344 * Format a double number. These methods call the NumberFormat
345 * pure virtual format() methods with the default FieldPosition.
347 * @param number The value to be formatted.
348 * @param appendTo Output parameter to receive result.
349 * Result is appended to existing contents.
350 * @return Reference to 'appendTo' parameter.
353 UnicodeString
& format( double number
,
354 UnicodeString
& appendTo
) const;
357 * Format a long number. These methods call the NumberFormat
358 * pure virtual format() methods with the default FieldPosition.
360 * @param number The value to be formatted.
361 * @param appendTo Output parameter to receive result.
362 * Result is appended to existing contents.
363 * @return Reference to 'appendTo' parameter.
366 UnicodeString
& format( int32_t number
,
367 UnicodeString
& appendTo
) const;
370 * Format an int64 number. These methods call the NumberFormat
371 * pure virtual format() methods with the default FieldPosition.
373 * @param number The value to be formatted.
374 * @param appendTo Output parameter to receive result.
375 * Result is appended to existing contents.
376 * @return Reference to 'appendTo' parameter.
379 UnicodeString
& format( int64_t number
,
380 UnicodeString
& appendTo
) const;
383 * Format a double number. Concrete subclasses must implement
384 * these pure virtual methods.
386 * @param number The value to be formatted.
387 * @param appendTo Output parameter to receive result.
388 * Result is appended to existing contents.
389 * @param pos On input: an alignment field, if desired.
390 * On output: the offsets of the alignment field.
391 * @return Reference to 'appendTo' parameter.
394 virtual UnicodeString
& format(double number
,
395 UnicodeString
& appendTo
,
396 FieldPosition
& pos
) const = 0;
398 * Format a double number. By default, the parent function simply
399 * calls the base class and does not return an error status.
400 * Therefore, the status may be ignored in some subclasses.
402 * @param number The value to be formatted.
403 * @param appendTo Output parameter to receive result.
404 * Result is appended to existing contents.
405 * @param pos On input: an alignment field, if desired.
406 * On output: the offsets of the alignment field.
407 * @param status error status
408 * @return Reference to 'appendTo' parameter.
411 virtual UnicodeString
& format(double number
,
412 UnicodeString
& appendTo
,
414 UErrorCode
&status
) const;
416 * Format a double number. Subclasses must implement
419 * @param number The value to be formatted.
420 * @param appendTo Output parameter to receive result.
421 * Result is appended to existing contents.
422 * @param posIter On return, can be used to iterate over positions
423 * of fields generated by this format call.
425 * @param status Output param filled with success/failure status.
426 * @return Reference to 'appendTo' parameter.
429 virtual UnicodeString
& format(double number
,
430 UnicodeString
& appendTo
,
431 FieldPositionIterator
* posIter
,
432 UErrorCode
& status
) const;
434 * Format a long number. Concrete subclasses must implement
435 * these pure virtual methods.
437 * @param number The value to be formatted.
438 * @param appendTo Output parameter to receive result.
439 * Result is appended to existing contents.
440 * @param pos On input: an alignment field, if desired.
441 * On output: the offsets of the alignment field.
442 * @return Reference to 'appendTo' parameter.
445 virtual UnicodeString
& format(int32_t number
,
446 UnicodeString
& appendTo
,
447 FieldPosition
& pos
) const = 0;
450 * Format a long number. Concrete subclasses may override
451 * this function to provide status return.
453 * @param number The value to be formatted.
454 * @param appendTo Output parameter to receive result.
455 * Result is appended to existing contents.
456 * @param pos On input: an alignment field, if desired.
457 * On output: the offsets of the alignment field.
458 * @param status the output status.
459 * @return Reference to 'appendTo' parameter.
462 virtual UnicodeString
& format(int32_t number
,
463 UnicodeString
& appendTo
,
465 UErrorCode
&status
) const;
468 * Format an int32 number. Subclasses must implement
471 * @param number The value to be formatted.
472 * @param appendTo Output parameter to receive result.
473 * Result is appended to existing contents.
474 * @param posIter On return, can be used to iterate over positions
475 * of fields generated by this format call.
477 * @param status Output param filled with success/failure status.
478 * @return Reference to 'appendTo' parameter.
481 virtual UnicodeString
& format(int32_t number
,
482 UnicodeString
& appendTo
,
483 FieldPositionIterator
* posIter
,
484 UErrorCode
& status
) const;
486 * Format an int64 number. (Not abstract to retain compatibility
487 * with earlier releases, however subclasses should override this
488 * method as it just delegates to format(int32_t number...);
490 * @param number The value to be formatted.
491 * @param appendTo Output parameter to receive result.
492 * Result is appended to existing contents.
493 * @param pos On input: an alignment field, if desired.
494 * On output: the offsets of the alignment field.
495 * @return Reference to 'appendTo' parameter.
498 virtual UnicodeString
& format(int64_t number
,
499 UnicodeString
& appendTo
,
500 FieldPosition
& pos
) const;
503 * Format an int64 number. (Not abstract to retain compatibility
504 * with earlier releases, however subclasses should override this
505 * method as it just delegates to format(int32_t number...);
507 * @param number The value to be formatted.
508 * @param appendTo Output parameter to receive result.
509 * Result is appended to existing contents.
510 * @param pos On input: an alignment field, if desired.
511 * On output: the offsets of the alignment field.
512 * @param status Output param filled with success/failure status.
513 * @return Reference to 'appendTo' parameter.
516 virtual UnicodeString
& format(int64_t number
,
517 UnicodeString
& appendTo
,
519 UErrorCode
& status
) const;
521 * Format an int64 number. Subclasses must implement
524 * @param number The value to be formatted.
525 * @param appendTo Output parameter to receive result.
526 * Result is appended to existing contents.
527 * @param posIter On return, can be used to iterate over positions
528 * of fields generated by this format call.
530 * @param status Output param filled with success/failure status.
531 * @return Reference to 'appendTo' parameter.
534 virtual UnicodeString
& format(int64_t number
,
535 UnicodeString
& appendTo
,
536 FieldPositionIterator
* posIter
,
537 UErrorCode
& status
) const;
540 * Format a decimal number. Subclasses must implement
541 * this method. The syntax of the unformatted number is a "numeric string"
542 * as defined in the Decimal Arithmetic Specification, available at
543 * http://speleotrove.com/decimal
545 * @param number The unformatted number, as a string, to be formatted.
546 * @param appendTo Output parameter to receive result.
547 * Result is appended to existing contents.
548 * @param posIter On return, can be used to iterate over positions
549 * of fields generated by this format call.
551 * @param status Output param filled with success/failure status.
552 * @return Reference to 'appendTo' parameter.
555 virtual UnicodeString
& format(StringPiece number
,
556 UnicodeString
& appendTo
,
557 FieldPositionIterator
* posIter
,
558 UErrorCode
& status
) const;
561 * Format a decimal number.
562 * The number is a DigitList wrapper onto a floating point decimal number.
563 * The default implementation in NumberFormat converts the decimal number
564 * to a double and formats that. Subclasses of NumberFormat that want
565 * to specifically handle big decimal numbers must override this method.
566 * class DecimalFormat does so.
568 * @param number The number, a DigitList format Decimal Floating Point.
569 * @param appendTo Output parameter to receive result.
570 * Result is appended to existing contents.
571 * @param posIter On return, can be used to iterate over positions
572 * of fields generated by this format call.
573 * @param status Output param filled with success/failure status.
574 * @return Reference to 'appendTo' parameter.
577 virtual UnicodeString
& format(const DigitList
&number
,
578 UnicodeString
& appendTo
,
579 FieldPositionIterator
* posIter
,
580 UErrorCode
& status
) const;
583 * Format a decimal number.
584 * The number is a DigitList wrapper onto a floating point decimal number.
585 * The default implementation in NumberFormat converts the decimal number
586 * to a double and formats that. Subclasses of NumberFormat that want
587 * to specifically handle big decimal numbers must override this method.
588 * class DecimalFormat does so.
590 * @param number The number, a DigitList format Decimal Floating Point.
591 * @param appendTo Output parameter to receive result.
592 * Result is appended to existing contents.
593 * @param pos On input: an alignment field, if desired.
594 * On output: the offsets of the alignment field.
595 * @param status Output param filled with success/failure status.
596 * @return Reference to 'appendTo' parameter.
599 virtual UnicodeString
& format(const DigitList
&number
,
600 UnicodeString
& appendTo
,
602 UErrorCode
& status
) const;
607 * Return a long if possible (e.g. within range LONG_MAX,
608 * LONG_MAX], and with no decimals), otherwise a double. If
609 * IntegerOnly is set, will stop at a decimal point (or equivalent;
610 * e.g. for rational numbers "1 2/3", will stop after the 1).
612 * If no object can be parsed, index is unchanged, and NULL is
615 * This is a pure virtual which concrete subclasses must implement.
617 * @param text The text to be parsed.
618 * @param result Formattable to be set to the parse result.
619 * If parse fails, return contents are undefined.
620 * @param parsePosition The position to start parsing at on input.
621 * On output, moved to after the last successfully
622 * parse character. On parse failure, does not change.
625 virtual void parse(const UnicodeString
& text
,
627 ParsePosition
& parsePosition
) const = 0;
630 * Parse a string as a numeric value, and return a Formattable
631 * numeric object. This method parses integers only if IntegerOnly
634 * @param text The text to be parsed.
635 * @param result Formattable to be set to the parse result.
636 * If parse fails, return contents are undefined.
637 * @param status Output parameter set to a failure error code
638 * when a failure occurs.
639 * @see NumberFormat::isParseIntegerOnly
642 virtual void parse(const UnicodeString
& text
,
644 UErrorCode
& status
) const;
647 * Parses text from the given string as a currency amount. Unlike
648 * the parse() method, this method will attempt to parse a generic
649 * currency name, searching for a match of this object's locale's
650 * currency display names, or for a 3-letter ISO currency code.
651 * This method will fail if this format is not a currency format,
652 * that is, if it does not contain the currency pattern symbol
653 * (U+00A4) in its prefix or suffix.
655 * @param text the string to parse
656 * @param pos input-output position; on input, the position within text
657 * to match; must have 0 <= pos.getIndex() < text.length();
658 * on output, the position after the last matched character.
659 * If the parse fails, the position in unchanged upon output.
660 * @return if parse succeeds, a pointer to a newly-created CurrencyAmount
661 * object (owned by the caller) containing information about
662 * the parsed currency; if parse fails, this is NULL.
665 virtual CurrencyAmount
* parseCurrency(const UnicodeString
& text
,
666 ParsePosition
& pos
) const;
669 * Return true if this format will parse numbers as integers
670 * only. For example in the English locale, with ParseIntegerOnly
671 * true, the string "1234." would be parsed as the integer value
672 * 1234 and parsing would stop at the "." character. Of course,
673 * the exact format accepted by the parse operation is locale
674 * dependant and determined by sub-classes of NumberFormat.
675 * @return true if this format will parse numbers as integers
679 UBool
isParseIntegerOnly(void) const;
682 * Sets whether or not numbers should be parsed as integers only.
683 * @param value set True, this format will parse numbers as integers
685 * @see isParseIntegerOnly
688 virtual void setParseIntegerOnly(UBool value
);
691 * Sets whether lenient parsing should be enabled (it is off by default).
693 * @param enable \c TRUE if lenient parsing should be used,
694 * \c FALSE otherwise.
697 virtual void setLenient(UBool enable
);
700 * Returns whether lenient parsing is enabled (it is off by default).
702 * @return \c TRUE if lenient parsing is enabled,
703 * \c FALSE otherwise.
707 virtual UBool
isLenient(void) const;
710 * Create a default style NumberFormat for the current default locale.
711 * The default formatting style is locale dependent.
713 * <strong>NOTE:</strong> New users are strongly encouraged to use
714 * {@link NumberFormatter} instead of NumberFormat.
717 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
720 * Create a default style NumberFormat for the specified locale.
721 * The default formatting style is locale dependent.
722 * @param inLocale the given locale.
724 * <strong>NOTE:</strong> New users are strongly encouraged to use
725 * {@link NumberFormatter} instead of NumberFormat.
728 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& inLocale
,
732 * Create a specific style NumberFormat for the specified locale.
734 * <strong>NOTE:</strong> New users are strongly encouraged to use
735 * {@link NumberFormatter} instead of NumberFormat.
736 * @param desiredLocale the given locale.
737 * @param style the given style.
738 * @param errorCode Output param filled with success/failure status.
739 * @return A new NumberFormat instance.
742 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
,
743 UNumberFormatStyle style
,
744 UErrorCode
& errorCode
);
746 #ifndef U_HIDE_INTERNAL_API
750 * Creates NumberFormat instance without using the cache.
753 static NumberFormat
* internalCreateInstance(
754 const Locale
& desiredLocale
,
755 UNumberFormatStyle style
,
756 UErrorCode
& errorCode
);
760 * Returns handle to the shared, cached NumberFormat instance for given
761 * locale. On success, caller must call removeRef() on returned value
762 * once it is done with the shared instance.
765 static const SharedNumberFormat
* U_EXPORT2
createSharedInstance(
766 const Locale
& inLocale
, UNumberFormatStyle style
, UErrorCode
& status
);
768 #endif /* U_HIDE_INTERNAL_API */
771 * Returns a currency format for the current default locale.
773 * <strong>NOTE:</strong> New users are strongly encouraged to use
774 * {@link NumberFormatter} instead of NumberFormat.
777 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
780 * Returns a currency format for the specified locale.
782 * <strong>NOTE:</strong> New users are strongly encouraged to use
783 * {@link NumberFormatter} instead of NumberFormat.
784 * @param inLocale the given locale.
787 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
791 * Returns a percentage format for the current default locale.
793 * <strong>NOTE:</strong> New users are strongly encouraged to use
794 * {@link NumberFormatter} instead of NumberFormat.
797 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
800 * Returns a percentage format for the specified locale.
802 * <strong>NOTE:</strong> New users are strongly encouraged to use
803 * {@link NumberFormatter} instead of NumberFormat.
804 * @param inLocale the given locale.
807 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
811 * Returns a scientific format for the current default locale.
813 * <strong>NOTE:</strong> New users are strongly encouraged to use
814 * {@link NumberFormatter} instead of NumberFormat.
817 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
820 * Returns a scientific format for the specified locale.
822 * <strong>NOTE:</strong> New users are strongly encouraged to use
823 * {@link NumberFormatter} instead of NumberFormat.
824 * @param inLocale the given locale.
827 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
831 * Get the set of Locales for which NumberFormats are installed.
832 * @param count Output param to receive the size of the locales
835 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
837 #if !UCONFIG_NO_SERVICE
839 * Register a new NumberFormatFactory. The factory will be adopted.
840 * Because ICU may choose to cache NumberFormat objects internally,
841 * this must be called at application startup, prior to any calls to
842 * NumberFormat::createInstance to avoid undefined behavior.
843 * @param toAdopt the NumberFormatFactory instance to be adopted
844 * @param status the in/out status code, no special meanings are assigned
845 * @return a registry key that can be used to unregister this factory
848 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
851 * Unregister a previously-registered NumberFormatFactory using the key returned from the
852 * register call. Key becomes invalid after a successful call and should not be used again.
853 * The NumberFormatFactory corresponding to the key will be deleted.
854 * Because ICU may choose to cache NumberFormat objects internally,
855 * this should be called during application shutdown, after all calls to
856 * NumberFormat::createInstance to avoid undefined behavior.
857 * @param key the registry key returned by a previous call to registerFactory
858 * @param status the in/out status code, no special meanings are assigned
859 * @return TRUE if the factory for the key was successfully unregistered
862 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
865 * Return a StringEnumeration over the locales available at the time of the call,
866 * including registered locales.
867 * @return a StringEnumeration over the locales available at the time of the call
870 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
871 #endif /* UCONFIG_NO_SERVICE */
874 * Returns true if grouping is used in this format. For example,
875 * in the English locale, with grouping on, the number 1234567
876 * might be formatted as "1,234,567". The grouping separator as
877 * well as the size of each group is locale dependent and is
878 * determined by sub-classes of NumberFormat.
879 * @see setGroupingUsed
882 UBool
isGroupingUsed(void) const;
885 * Set whether or not grouping will be used in this format.
886 * @param newValue True, grouping will be used in this format.
887 * @see getGroupingUsed
890 virtual void setGroupingUsed(UBool newValue
);
893 * Returns the maximum number of digits allowed in the integer portion of a
895 * @return the maximum number of digits allowed in the integer portion of a
897 * @see setMaximumIntegerDigits
900 int32_t getMaximumIntegerDigits(void) const;
903 * Sets the maximum number of digits allowed in the integer portion of a
904 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
905 * new value for maximumIntegerDigits is less than the current value
906 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
909 * @param newValue the new value for the maximum number of digits
910 * allowed in the integer portion of a number.
911 * @see getMaximumIntegerDigits
914 virtual void setMaximumIntegerDigits(int32_t newValue
);
917 * Returns the minimum number of digits allowed in the integer portion of a
919 * @return the minimum number of digits allowed in the integer portion of a
921 * @see setMinimumIntegerDigits
924 int32_t getMinimumIntegerDigits(void) const;
927 * Sets the minimum number of digits allowed in the integer portion of a
928 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
929 * new value for minimumIntegerDigits exceeds the current value
930 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
932 * @param newValue the new value to be set.
933 * @see getMinimumIntegerDigits
936 virtual void setMinimumIntegerDigits(int32_t newValue
);
939 * Returns the maximum number of digits allowed in the fraction portion of a
941 * @return the maximum number of digits allowed in the fraction portion of a
943 * @see setMaximumFractionDigits
946 int32_t getMaximumFractionDigits(void) const;
949 * Sets the maximum number of digits allowed in the fraction portion of a
950 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
951 * new value for maximumFractionDigits is less than the current value
952 * of minimumFractionDigits, then minimumFractionDigits will also be set to
954 * @param newValue the new value to be set.
955 * @see getMaximumFractionDigits
958 virtual void setMaximumFractionDigits(int32_t newValue
);
961 * Returns the minimum number of digits allowed in the fraction portion of a
963 * @return the minimum number of digits allowed in the fraction portion of a
965 * @see setMinimumFractionDigits
968 int32_t getMinimumFractionDigits(void) const;
971 * Sets the minimum number of digits allowed in the fraction portion of a
972 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
973 * new value for minimumFractionDigits exceeds the current value
974 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
976 * @param newValue the new value to be set.
977 * @see getMinimumFractionDigits
980 virtual void setMinimumFractionDigits(int32_t newValue
);
983 * Sets the currency used to display currency
984 * amounts. This takes effect immediately, if this format is a
985 * currency format. If this format is not a currency format, then
986 * the currency is used if and when this object becomes a
988 * @param theCurrency a 3-letter ISO code indicating new currency
989 * to use. It need not be null-terminated. May be the empty
990 * string or NULL to indicate no currency.
991 * @param ec input-output error code
994 virtual void setCurrency(const char16_t* theCurrency
, UErrorCode
& ec
);
997 * Gets the currency used to display currency
998 * amounts. This may be an empty string for some subclasses.
999 * @return a 3-letter null-terminated ISO code indicating
1000 * the currency in use, or a pointer to the empty string.
1003 const char16_t* getCurrency() const;
1006 * Set a particular UDisplayContext value in the formatter, such as
1007 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
1008 * @param value The UDisplayContext value to set.
1009 * @param status Input/output status. If at entry this indicates a failure
1010 * status, the function will do nothing; otherwise this will be
1011 * updated with any new status from the function.
1014 virtual void setContext(UDisplayContext value
, UErrorCode
& status
);
1017 * Get the formatter's UDisplayContext value for the specified UDisplayContextType,
1018 * such as UDISPCTX_TYPE_CAPITALIZATION.
1019 * @param type The UDisplayContextType whose value to return
1020 * @param status Input/output status. If at entry this indicates a failure
1021 * status, the function will do nothing; otherwise this will be
1022 * updated with any new status from the function.
1023 * @return The UDisplayContextValue for the specified type.
1026 virtual UDisplayContext
getContext(UDisplayContextType type
, UErrorCode
& status
) const;
1029 * Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary
1030 * if the subclass does not support rounding.
1031 * @return A rounding mode
1034 virtual ERoundingMode
getRoundingMode(void) const;
1037 * Set the rounding mode. If a subclass does not support rounding, this will do nothing.
1038 * @param roundingMode A rounding mode
1041 virtual void setRoundingMode(ERoundingMode roundingMode
);
1046 * Return the class ID for this class. This is useful for
1047 * comparing to a return value from getDynamicClassID(). Note that,
1048 * because NumberFormat is an abstract base class, no fully constructed object
1049 * will have the class ID returned by NumberFormat::getStaticClassID().
1050 * @return The class ID for all objects of this class.
1053 static UClassID U_EXPORT2
getStaticClassID(void);
1056 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
1057 * This method is to implement a simple version of RTTI, since not all
1058 * C++ compilers support genuine RTTI. Polymorphic operator==() and
1059 * clone() methods call this method.
1061 * @return The class ID for this object. All objects of a
1062 * given class have the same class ID. Objects of
1063 * other classes have different class IDs.
1066 virtual UClassID
getDynamicClassID(void) const = 0;
1071 * Default constructor for subclass use only.
1080 NumberFormat(const NumberFormat
&);
1083 * Assignment operator.
1086 NumberFormat
& operator=(const NumberFormat
&);
1089 * Returns the currency in effect for this formatter. Subclasses
1090 * should override this method as needed. Unlike getCurrency(),
1091 * this method should never return "".
1092 * @result output parameter for null-terminated result, which must
1093 * have a capacity of at least 4
1096 virtual void getEffectiveCurrency(char16_t* result
, UErrorCode
& ec
) const;
1098 #ifndef U_HIDE_INTERNAL_API
1100 * Creates the specified number format style of the desired locale.
1101 * If mustBeDecimalFormat is TRUE, then the returned pointer is
1102 * either a DecimalFormat or it is NULL.
1105 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1106 UNumberFormatStyle style
,
1107 UBool mustBeDecimalFormat
,
1108 UErrorCode
& errorCode
);
1109 #endif /* U_HIDE_INTERNAL_API */
1113 static UBool
isStyleSupported(UNumberFormatStyle style
);
1116 * Creates the specified decimal format style of the desired locale.
1117 * @param desiredLocale the given locale.
1118 * @param style the given style.
1119 * @param errorCode Output param filled with success/failure status.
1120 * @return A new NumberFormat instance.
1122 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1123 UNumberFormatStyle style
,
1124 UErrorCode
& errorCode
);
1126 UBool fGroupingUsed
;
1127 int32_t fMaxIntegerDigits
;
1128 int32_t fMinIntegerDigits
;
1129 int32_t fMaxFractionDigits
;
1130 int32_t fMinFractionDigits
;
1134 static const int32_t gDefaultMaxIntegerDigits
;
1136 static const int32_t gDefaultMinIntegerDigits
;
1139 UBool fParseIntegerOnly
;
1140 UBool fLenient
; // TRUE => lenient parse is enabled
1142 // ISO currency code
1143 char16_t fCurrency
[4];
1145 UDisplayContext fCapitalizationContext
;
1147 friend class ICUNumberFormatFactory
; // access to makeInstance
1148 friend class ICUNumberFormatService
;
1149 friend class ::NumberFormatTest
; // access to isStyleSupported()
1152 #if !UCONFIG_NO_SERVICE
1154 * A NumberFormatFactory is used to register new number formats. The factory
1155 * should be able to create any of the predefined formats for each locale it
1156 * supports. When registered, the locales it supports extend or override the
1157 * locale already supported by ICU.
1161 class U_I18N_API NumberFormatFactory
: public UObject
{
1168 virtual ~NumberFormatFactory();
1171 * Return true if this factory will be visible. Default is true.
1172 * If not visible, the locales supported by this factory will not
1173 * be listed by getAvailableLocales.
1176 virtual UBool
visible(void) const = 0;
1179 * Return the locale names directly supported by this factory. The number of names
1180 * is returned in count;
1183 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
1186 * Return a number format of the appropriate type. If the locale
1187 * is not supported, return null. If the locale is supported, but
1188 * the type is not provided by this service, return null. Otherwise
1189 * return an appropriate instance of NumberFormat.
1192 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
1196 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
1199 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
1202 * True if the locale supported by this factory is visible.
1205 const UBool _visible
;
1208 * The locale supported by this factory, as a UnicodeString.
1217 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
1222 virtual ~SimpleNumberFormatFactory();
1227 virtual UBool
visible(void) const;
1232 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
1234 #endif /* #if !UCONFIG_NO_SERVICE */
1236 // -------------------------------------
1239 NumberFormat::isParseIntegerOnly() const
1241 return fParseIntegerOnly
;
1245 NumberFormat::isLenient() const
1251 #endif // U_SHOW_CPLUSPLUS_API
1253 #endif /* #if !UCONFIG_NO_FORMATTING */