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.
61 * Abstract base class for all number formats. Provides interface for
62 * formatting and parsing a number. Also provides methods for
63 * determining which locales have number formats, and what their names
66 * \headerfile unicode/numfmt.h "unicode/numfmt.h"
68 * NumberFormat helps you to format and parse numbers for any locale.
69 * Your code can be completely independent of the locale conventions
70 * for decimal points, thousands-separators, or even the particular
71 * decimal digits used, or whether the number format is even decimal.
73 * To format a number for the current Locale, use one of the static
77 * #include "unicode/numfmt.h"
78 * #include "unicode/unistr.h"
79 * #include "unicode/ustream.h"
80 * using namespace std;
83 * double myNumber = 7.0;
84 * UnicodeString myString;
85 * UErrorCode success = U_ZERO_ERROR;
86 * NumberFormat* nf = NumberFormat::createInstance(success);
87 * nf->format(myNumber, myString);
88 * cout << " Example 1: " << myString << endl;
91 * Note that there are additional factory methods within subclasses of
94 * If you are formatting multiple numbers, it is more efficient to get
95 * the format and use it multiple times so that the system doesn't
96 * have to fetch the information about the local language and country
97 * conventions multiple times.
99 * UnicodeString myString;
100 * UErrorCode success = U_ZERO_ERROR;
101 * NumberFormat *nf = NumberFormat::createInstance( success );
102 * for (int32_t number: {123, 3333, -1234567}) {
103 * nf->format(number, myString);
106 * cout << " Example 2: " << myString << endl;
108 * To format a number for a different Locale, specify it in the
109 * call to \c createInstance().
111 * nf = NumberFormat::createInstance(Locale::getFrench(), success);
113 * You can use a \c NumberFormat to parse also.
115 * UErrorCode success;
116 * Formattable result(-999); // initialized with error code
117 * nf->parse(myString, result, success);
119 * Use \c createInstance() to get the normal number format for a \c Locale.
120 * There are other static factory methods available. Use \c createCurrencyInstance()
121 * to get the currency number format for that country. Use \c createPercentInstance()
122 * to get a format for displaying percentages. With this format, a
123 * fraction from 0.53 is displayed as 53%.
125 * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance().
127 * \c createInstance(locale, UNUM_DECIMAL, errorCode) to get the normal number format,\n
128 * \c createInstance(locale, UNUM_PERCENT, errorCode) to get a format for displaying percentage,\n
129 * \c createInstance(locale, UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,\n
130 * \c createInstance(locale, UNUM_CURRENCY, errorCode) to get the currency number format,
131 * in which the currency is represented by its symbol, for example, "$3.00".\n
132 * \c createInstance(locale, UNUM_CURRENCY_ISO, errorCode) to get the currency number format,
133 * in which the currency is represented by its ISO code, for example "USD3.00".\n
134 * \c createInstance(locale, UNUM_CURRENCY_PLURAL, errorCode) to get the currency number format,
135 * in which the currency is represented by its full name in plural format,
136 * for example, "3.00 US dollars" or "1.00 US dollar".
138 * You can also control the display of numbers with such methods as
139 * \c getMinimumFractionDigits(). If you want even more control over the
140 * format or parsing, or want to give your users more control, you can
141 * try dynamic_casting the \c NumberFormat you get from the factory methods to a
142 * \c DecimalFormat. This will work for the vast majority of
143 * countries; just remember to test for NULL in case you
144 * encounter an unusual one.
146 * You can also use forms of the parse and format methods with
147 * \c ParsePosition and \c FieldPosition to allow you to:
149 * <li>(a) progressively parse through pieces of a string.
150 * <li>(b) align the decimal point and other areas.
152 * For example, you can align numbers in two ways.
154 * If you are using a monospaced font with spacing for alignment, you
155 * can pass the \c FieldPosition in your format call, with field =
156 * \c UNUM_INTEGER_FIELD. On output, \c getEndIndex will be set to the offset
157 * between the last character of the integer and the decimal. Add
158 * (desiredSpaceCount - getEndIndex) spaces at the front of the
161 * If you are using proportional fonts, instead of padding with
162 * spaces, measure the width of the string in pixels from the start to
163 * getEndIndex. Then move the pen by (desiredPixelWidth -
164 * widthToAlignmentPoint) before drawing the text. It also works
165 * where there is no decimal, but possibly additional characters at
166 * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
168 * <em>User subclasses are not supported.</em> While clients may write
169 * subclasses, such code will not necessarily work and will not be
170 * guaranteed to work stably from release to release.
174 class U_I18N_API NumberFormat
: public Format
{
180 * For more detail on rounding modes, see:
181 * http://userguide.icu-project.org/formatparse/numbers/rounding-modes
186 kRoundCeiling
, /**< Round towards positive infinity */
187 kRoundFloor
, /**< Round towards negative infinity */
188 kRoundDown
, /**< Round towards zero */
189 kRoundUp
, /**< Round away from zero */
190 kRoundHalfEven
, /**< Round towards the nearest integer, or
191 towards the nearest even integer if equidistant */
192 kRoundHalfDown
, /**< Round towards the nearest integer, or
193 towards zero if equidistant */
194 kRoundHalfUp
, /**< Round towards the nearest integer, or
195 away from zero if equidistant */
197 * Return U_FORMAT_INEXACT_ERROR if number does not format exactly.
204 * Alignment Field constants used to construct a FieldPosition object.
205 * Signifies that the position of the integer part or fraction part of
206 * a formatted number should be returned.
208 * Note: as of ICU 4.4, the values in this enum have been extended to
209 * support identification of all number format fields, not just those
210 * pertaining to alignment.
212 * These constants are provided for backwards compatibility only.
213 * Please use the C style constants defined in the header file unum.h.
218 enum EAlignmentFields
{
219 /** @stable ICU 2.0 */
220 kIntegerField
= UNUM_INTEGER_FIELD
,
221 /** @stable ICU 2.0 */
222 kFractionField
= UNUM_FRACTION_FIELD
,
223 /** @stable ICU 2.0 */
224 kDecimalSeparatorField
= UNUM_DECIMAL_SEPARATOR_FIELD
,
225 /** @stable ICU 2.0 */
226 kExponentSymbolField
= UNUM_EXPONENT_SYMBOL_FIELD
,
227 /** @stable ICU 2.0 */
228 kExponentSignField
= UNUM_EXPONENT_SIGN_FIELD
,
229 /** @stable ICU 2.0 */
230 kExponentField
= UNUM_EXPONENT_FIELD
,
231 /** @stable ICU 2.0 */
232 kGroupingSeparatorField
= UNUM_GROUPING_SEPARATOR_FIELD
,
233 /** @stable ICU 2.0 */
234 kCurrencyField
= UNUM_CURRENCY_FIELD
,
235 /** @stable ICU 2.0 */
236 kPercentField
= UNUM_PERCENT_FIELD
,
237 /** @stable ICU 2.0 */
238 kPermillField
= UNUM_PERMILL_FIELD
,
239 /** @stable ICU 2.0 */
240 kSignField
= UNUM_SIGN_FIELD
,
241 #ifndef U_HIDE_DRAFT_API
243 kMeasureUnitField
= UNUM_MEASURE_UNIT_FIELD
,
245 kCompactField
= UNUM_COMPACT_FIELD
,
246 #endif // U_HIDE_DRAFT_API
249 * These constants are provided for backwards compatibility only.
250 * Please use the constants defined in the header file unum.h.
252 /** @stable ICU 2.0 */
253 INTEGER_FIELD
= UNUM_INTEGER_FIELD
,
254 /** @stable ICU 2.0 */
255 FRACTION_FIELD
= UNUM_FRACTION_FIELD
262 virtual ~NumberFormat();
265 * Return true if the given Format objects are semantically equal.
266 * Objects of different subclasses are considered unequal.
267 * @return true if the given Format objects are semantically equal.
270 virtual UBool
operator==(const Format
& other
) const;
273 using Format::format
;
276 * Format an object to produce a string. This method handles
277 * Formattable objects with numeric types. If the Formattable
278 * object type is not a numeric type, then it returns a failing
281 * @param obj The object to format.
282 * @param appendTo Output parameter to receive result.
283 * Result is appended to existing contents.
284 * @param pos On input: an alignment field, if desired.
285 * On output: the offsets of the alignment field.
286 * @param status Output param filled with success/failure status.
287 * @return Reference to 'appendTo' parameter.
290 virtual UnicodeString
& format(const Formattable
& obj
,
291 UnicodeString
& appendTo
,
293 UErrorCode
& status
) const;
296 * Format an object to produce a string. This method handles
297 * Formattable objects with numeric types. If the Formattable
298 * object type is not a numeric type, then it returns a failing
301 * @param obj The object to format.
302 * @param appendTo Output parameter to receive result.
303 * Result is appended to existing contents.
304 * @param posIter On return, can be used to iterate over positions
305 * of fields generated by this format call. Can be
307 * @param status Output param filled with success/failure status.
308 * @return Reference to 'appendTo' parameter.
311 virtual UnicodeString
& format(const Formattable
& obj
,
312 UnicodeString
& appendTo
,
313 FieldPositionIterator
* posIter
,
314 UErrorCode
& status
) const;
317 * Parse a string to produce an object. This methods handles
318 * parsing of numeric strings into Formattable objects with numeric
321 * Before calling, set parse_pos.index to the offset you want to
322 * start parsing at in the source. After calling, parse_pos.index
323 * indicates the position after the successfully parsed text. If
324 * an error occurs, parse_pos.index is unchanged.
326 * When parsing, leading whitespace is discarded (with successful
327 * parse), while trailing whitespace is left as is.
329 * See Format::parseObject() for more.
331 * @param source The string to be parsed into an object.
332 * @param result Formattable to be set to the parse result.
333 * If parse fails, return contents are undefined.
334 * @param parse_pos The position to start parsing at. Upon return
335 * this param is set to the position after the
336 * last character successfully parsed. If the
337 * source is not parsed successfully, this param
338 * will remain unchanged.
339 * @return A newly created Formattable* object, or NULL
340 * on failure. The caller owns this and should
341 * delete it when done.
344 virtual void parseObject(const UnicodeString
& source
,
346 ParsePosition
& parse_pos
) const;
349 * Format a double number. These methods call the NumberFormat
350 * pure virtual format() methods with the default FieldPosition.
352 * @param number The value to be formatted.
353 * @param appendTo Output parameter to receive result.
354 * Result is appended to existing contents.
355 * @return Reference to 'appendTo' parameter.
358 UnicodeString
& format( double number
,
359 UnicodeString
& appendTo
) const;
362 * Format a long number. These methods call the NumberFormat
363 * pure virtual format() methods with the default FieldPosition.
365 * @param number The value to be formatted.
366 * @param appendTo Output parameter to receive result.
367 * Result is appended to existing contents.
368 * @return Reference to 'appendTo' parameter.
371 UnicodeString
& format( int32_t number
,
372 UnicodeString
& appendTo
) const;
375 * Format an int64 number. These methods call the NumberFormat
376 * pure virtual format() methods with the default FieldPosition.
378 * @param number The value to be formatted.
379 * @param appendTo Output parameter to receive result.
380 * Result is appended to existing contents.
381 * @return Reference to 'appendTo' parameter.
384 UnicodeString
& format( int64_t number
,
385 UnicodeString
& appendTo
) const;
388 * Format a double number. Concrete subclasses must implement
389 * these pure virtual methods.
391 * @param number The value to be formatted.
392 * @param appendTo Output parameter to receive result.
393 * Result is appended to existing contents.
394 * @param pos On input: an alignment field, if desired.
395 * On output: the offsets of the alignment field.
396 * @return Reference to 'appendTo' parameter.
399 virtual UnicodeString
& format(double number
,
400 UnicodeString
& appendTo
,
401 FieldPosition
& pos
) const = 0;
403 * Format a double number. By default, the parent function simply
404 * calls the base class and does not return an error status.
405 * Therefore, the status may be ignored in some subclasses.
407 * @param number The value to be formatted.
408 * @param appendTo Output parameter to receive result.
409 * Result is appended to existing contents.
410 * @param pos On input: an alignment field, if desired.
411 * On output: the offsets of the alignment field.
412 * @param status error status
413 * @return Reference to 'appendTo' parameter.
416 virtual UnicodeString
& format(double number
,
417 UnicodeString
& appendTo
,
419 UErrorCode
&status
) const;
421 * Format a double number. Subclasses must implement
424 * @param number The value to be formatted.
425 * @param appendTo Output parameter to receive result.
426 * Result is appended to existing contents.
427 * @param posIter On return, can be used to iterate over positions
428 * of fields generated by this format call.
430 * @param status Output param filled with success/failure status.
431 * @return Reference to 'appendTo' parameter.
434 virtual UnicodeString
& format(double number
,
435 UnicodeString
& appendTo
,
436 FieldPositionIterator
* posIter
,
437 UErrorCode
& status
) const;
439 * Format a long number. Concrete subclasses must implement
440 * these pure virtual methods.
442 * @param number The value to be formatted.
443 * @param appendTo Output parameter to receive result.
444 * Result is appended to existing contents.
445 * @param pos On input: an alignment field, if desired.
446 * On output: the offsets of the alignment field.
447 * @return Reference to 'appendTo' parameter.
450 virtual UnicodeString
& format(int32_t number
,
451 UnicodeString
& appendTo
,
452 FieldPosition
& pos
) const = 0;
455 * Format a long number. Concrete subclasses may override
456 * this function to provide status return.
458 * @param number The value to be formatted.
459 * @param appendTo Output parameter to receive result.
460 * Result is appended to existing contents.
461 * @param pos On input: an alignment field, if desired.
462 * On output: the offsets of the alignment field.
463 * @param status the output status.
464 * @return Reference to 'appendTo' parameter.
467 virtual UnicodeString
& format(int32_t number
,
468 UnicodeString
& appendTo
,
470 UErrorCode
&status
) const;
473 * Format an int32 number. Subclasses must implement
476 * @param number The value to be formatted.
477 * @param appendTo Output parameter to receive result.
478 * Result is appended to existing contents.
479 * @param posIter On return, can be used to iterate over positions
480 * of fields generated by this format call.
482 * @param status Output param filled with success/failure status.
483 * @return Reference to 'appendTo' parameter.
486 virtual UnicodeString
& format(int32_t number
,
487 UnicodeString
& appendTo
,
488 FieldPositionIterator
* posIter
,
489 UErrorCode
& status
) const;
491 * Format an int64 number. (Not abstract to retain compatibility
492 * with earlier releases, however subclasses should override this
493 * method as it just delegates to format(int32_t number...);
495 * @param number The value to be formatted.
496 * @param appendTo Output parameter to receive result.
497 * Result is appended to existing contents.
498 * @param pos On input: an alignment field, if desired.
499 * On output: the offsets of the alignment field.
500 * @return Reference to 'appendTo' parameter.
503 virtual UnicodeString
& format(int64_t number
,
504 UnicodeString
& appendTo
,
505 FieldPosition
& pos
) const;
508 * Format an int64 number. (Not abstract to retain compatibility
509 * with earlier releases, however subclasses should override this
510 * method as it just delegates to format(int32_t number...);
512 * @param number The value to be formatted.
513 * @param appendTo Output parameter to receive result.
514 * Result is appended to existing contents.
515 * @param pos On input: an alignment field, if desired.
516 * On output: the offsets of the alignment field.
517 * @param status Output param filled with success/failure status.
518 * @return Reference to 'appendTo' parameter.
521 virtual UnicodeString
& format(int64_t number
,
522 UnicodeString
& appendTo
,
524 UErrorCode
& status
) const;
526 * Format an int64 number. Subclasses must implement
529 * @param number The value to be formatted.
530 * @param appendTo Output parameter to receive result.
531 * Result is appended to existing contents.
532 * @param posIter On return, can be used to iterate over positions
533 * of fields generated by this format call.
535 * @param status Output param filled with success/failure status.
536 * @return Reference to 'appendTo' parameter.
539 virtual UnicodeString
& format(int64_t number
,
540 UnicodeString
& appendTo
,
541 FieldPositionIterator
* posIter
,
542 UErrorCode
& status
) const;
545 * Format a decimal number. Subclasses must implement
546 * this method. The syntax of the unformatted number is a "numeric string"
547 * as defined in the Decimal Arithmetic Specification, available at
548 * http://speleotrove.com/decimal
550 * @param number The unformatted number, as a string, to be formatted.
551 * @param appendTo Output parameter to receive result.
552 * Result is appended to existing contents.
553 * @param posIter On return, can be used to iterate over positions
554 * of fields generated by this format call.
556 * @param status Output param filled with success/failure status.
557 * @return Reference to 'appendTo' parameter.
560 virtual UnicodeString
& format(StringPiece number
,
561 UnicodeString
& appendTo
,
562 FieldPositionIterator
* posIter
,
563 UErrorCode
& status
) const;
565 // Can't use #ifndef U_HIDE_INTERNAL_API because these are virtual methods
568 * Format a decimal number.
569 * The number is a DecimalQuantity wrapper onto a floating point decimal number.
570 * The default implementation in NumberFormat converts the decimal number
571 * to a double and formats that. Subclasses of NumberFormat that want
572 * to specifically handle big decimal numbers must override this method.
573 * class DecimalFormat does so.
575 * @param number The number, a DecimalQuantity format Decimal Floating Point.
576 * @param appendTo Output parameter to receive result.
577 * Result is appended to existing contents.
578 * @param posIter On return, can be used to iterate over positions
579 * of fields generated by this format call.
580 * @param status Output param filled with success/failure status.
581 * @return Reference to 'appendTo' parameter.
584 virtual UnicodeString
& format(const number::impl::DecimalQuantity
&number
,
585 UnicodeString
& appendTo
,
586 FieldPositionIterator
* posIter
,
587 UErrorCode
& status
) const;
590 * Format a decimal number.
591 * The number is a DecimalQuantity wrapper onto a floating point decimal number.
592 * The default implementation in NumberFormat converts the decimal number
593 * to a double and formats that. Subclasses of NumberFormat that want
594 * to specifically handle big decimal numbers must override this method.
595 * class DecimalFormat does so.
597 * @param number The number, a DecimalQuantity format Decimal Floating Point.
598 * @param appendTo Output parameter to receive result.
599 * Result is appended to existing contents.
600 * @param pos On input: an alignment field, if desired.
601 * On output: the offsets of the alignment field.
602 * @param status Output param filled with success/failure status.
603 * @return Reference to 'appendTo' parameter.
606 virtual UnicodeString
& format(const number::impl::DecimalQuantity
&number
,
607 UnicodeString
& appendTo
,
609 UErrorCode
& status
) const;
612 * Return a long if possible (e.g. within range LONG_MAX,
613 * LONG_MAX], and with no decimals), otherwise a double. If
614 * IntegerOnly is set, will stop at a decimal point (or equivalent;
615 * e.g. for rational numbers "1 2/3", will stop after the 1).
617 * If no object can be parsed, index is unchanged, and NULL is
620 * This is a pure virtual which concrete subclasses must implement.
622 * @param text The text to be parsed.
623 * @param result Formattable to be set to the parse result.
624 * If parse fails, return contents are undefined.
625 * @param parsePosition The position to start parsing at on input.
626 * On output, moved to after the last successfully
627 * parse character. On parse failure, does not change.
630 virtual void parse(const UnicodeString
& text
,
632 ParsePosition
& parsePosition
) const = 0;
635 * Parse a string as a numeric value, and return a Formattable
636 * numeric object. This method parses integers only if IntegerOnly
639 * @param text The text to be parsed.
640 * @param result Formattable to be set to the parse result.
641 * If parse fails, return contents are undefined.
642 * @param status Output parameter set to a failure error code
643 * when a failure occurs.
644 * @see NumberFormat::isParseIntegerOnly
647 virtual void parse(const UnicodeString
& text
,
649 UErrorCode
& status
) const;
652 * Parses text from the given string as a currency amount. Unlike
653 * the parse() method, this method will attempt to parse a generic
654 * currency name, searching for a match of this object's locale's
655 * currency display names, or for a 3-letter ISO currency code.
656 * This method will fail if this format is not a currency format,
657 * that is, if it does not contain the currency pattern symbol
658 * (U+00A4) in its prefix or suffix.
660 * @param text the string to parse
661 * @param pos input-output position; on input, the position within text
662 * to match; must have 0 <= pos.getIndex() < text.length();
663 * on output, the position after the last matched character.
664 * If the parse fails, the position in unchanged upon output.
665 * @return if parse succeeds, a pointer to a newly-created CurrencyAmount
666 * object (owned by the caller) containing information about
667 * the parsed currency; if parse fails, this is NULL.
670 virtual CurrencyAmount
* parseCurrency(const UnicodeString
& text
,
671 ParsePosition
& pos
) const;
674 * Return true if this format will parse numbers as integers
675 * only. For example in the English locale, with ParseIntegerOnly
676 * true, the string "1234." would be parsed as the integer value
677 * 1234 and parsing would stop at the "." character. Of course,
678 * the exact format accepted by the parse operation is locale
679 * dependant and determined by sub-classes of NumberFormat.
680 * @return true if this format will parse numbers as integers
684 UBool
isParseIntegerOnly(void) const;
687 * Sets whether or not numbers should be parsed as integers only.
688 * @param value set True, this format will parse numbers as integers
690 * @see isParseIntegerOnly
693 virtual void setParseIntegerOnly(UBool value
);
696 * Sets whether lenient parsing should be enabled (it is off by default).
698 * @param enable \c TRUE if lenient parsing should be used,
699 * \c FALSE otherwise.
702 virtual void setLenient(UBool enable
);
705 * Returns whether lenient parsing is enabled (it is off by default).
707 * @return \c TRUE if lenient parsing is enabled,
708 * \c FALSE otherwise.
712 virtual UBool
isLenient(void) const;
715 * Create a default style NumberFormat for the current default locale.
716 * The default formatting style is locale dependent.
718 * <strong>NOTE:</strong> New users are strongly encouraged to use
719 * {@link icu::number::NumberFormatter} instead of NumberFormat.
722 static NumberFormat
* U_EXPORT2
createInstance(UErrorCode
&);
725 * Create a default style NumberFormat for the specified locale.
726 * The default formatting style is locale dependent.
727 * @param inLocale the given locale.
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(const Locale
& inLocale
,
737 * Create a specific style NumberFormat for the specified locale.
739 * <strong>NOTE:</strong> New users are strongly encouraged to use
740 * {@link icu::number::NumberFormatter} instead of NumberFormat.
741 * @param desiredLocale the given locale.
742 * @param style the given style.
743 * @param errorCode Output param filled with success/failure status.
744 * @return A new NumberFormat instance.
747 static NumberFormat
* U_EXPORT2
createInstance(const Locale
& desiredLocale
,
748 UNumberFormatStyle style
,
749 UErrorCode
& errorCode
);
751 #ifndef U_HIDE_INTERNAL_API
755 * Creates NumberFormat instance without using the cache.
758 static NumberFormat
* internalCreateInstance(
759 const Locale
& desiredLocale
,
760 UNumberFormatStyle style
,
761 UErrorCode
& errorCode
);
765 * Returns handle to the shared, cached NumberFormat instance for given
766 * locale. On success, caller must call removeRef() on returned value
767 * once it is done with the shared instance.
770 static const SharedNumberFormat
* U_EXPORT2
createSharedInstance(
771 const Locale
& inLocale
, UNumberFormatStyle style
, UErrorCode
& status
);
773 #endif /* U_HIDE_INTERNAL_API */
776 * Returns a currency format for the current default locale.
778 * <strong>NOTE:</strong> New users are strongly encouraged to use
779 * {@link icu::number::NumberFormatter} instead of NumberFormat.
782 static NumberFormat
* U_EXPORT2
createCurrencyInstance(UErrorCode
&);
785 * Returns a currency format for the specified locale.
787 * <strong>NOTE:</strong> New users are strongly encouraged to use
788 * {@link icu::number::NumberFormatter} instead of NumberFormat.
789 * @param inLocale the given locale.
792 static NumberFormat
* U_EXPORT2
createCurrencyInstance(const Locale
& inLocale
,
796 * Returns a percentage format for the current default locale.
798 * <strong>NOTE:</strong> New users are strongly encouraged to use
799 * {@link icu::number::NumberFormatter} instead of NumberFormat.
802 static NumberFormat
* U_EXPORT2
createPercentInstance(UErrorCode
&);
805 * Returns a percentage format for the specified locale.
807 * <strong>NOTE:</strong> New users are strongly encouraged to use
808 * {@link icu::number::NumberFormatter} instead of NumberFormat.
809 * @param inLocale the given locale.
812 static NumberFormat
* U_EXPORT2
createPercentInstance(const Locale
& inLocale
,
816 * Returns a scientific format for the current default locale.
818 * <strong>NOTE:</strong> New users are strongly encouraged to use
819 * {@link icu::number::NumberFormatter} instead of NumberFormat.
822 static NumberFormat
* U_EXPORT2
createScientificInstance(UErrorCode
&);
825 * Returns a scientific format for the specified locale.
827 * <strong>NOTE:</strong> New users are strongly encouraged to use
828 * {@link icu::number::NumberFormatter} instead of NumberFormat.
829 * @param inLocale the given locale.
832 static NumberFormat
* U_EXPORT2
createScientificInstance(const Locale
& inLocale
,
836 * Get the set of Locales for which NumberFormats are installed.
837 * @param count Output param to receive the size of the locales
840 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
842 #if !UCONFIG_NO_SERVICE
844 * Register a new NumberFormatFactory. The factory will be adopted.
845 * Because ICU may choose to cache NumberFormat objects internally,
846 * this must be called at application startup, prior to any calls to
847 * NumberFormat::createInstance to avoid undefined behavior.
848 * @param toAdopt the NumberFormatFactory instance to be adopted
849 * @param status the in/out status code, no special meanings are assigned
850 * @return a registry key that can be used to unregister this factory
853 static URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory
* toAdopt
, UErrorCode
& status
);
856 * Unregister a previously-registered NumberFormatFactory using the key returned from the
857 * register call. Key becomes invalid after a successful call and should not be used again.
858 * The NumberFormatFactory corresponding to the key will be deleted.
859 * Because ICU may choose to cache NumberFormat objects internally,
860 * this should be called during application shutdown, after all calls to
861 * NumberFormat::createInstance to avoid undefined behavior.
862 * @param key the registry key returned by a previous call to registerFactory
863 * @param status the in/out status code, no special meanings are assigned
864 * @return TRUE if the factory for the key was successfully unregistered
867 static UBool U_EXPORT2
unregister(URegistryKey key
, UErrorCode
& status
);
870 * Return a StringEnumeration over the locales available at the time of the call,
871 * including registered locales.
872 * @return a StringEnumeration over the locales available at the time of the call
875 static StringEnumeration
* U_EXPORT2
getAvailableLocales(void);
876 #endif /* UCONFIG_NO_SERVICE */
879 * Returns true if grouping is used in this format. For example,
880 * in the English locale, with grouping on, the number 1234567
881 * might be formatted as "1,234,567". The grouping separator as
882 * well as the size of each group is locale dependent and is
883 * determined by sub-classes of NumberFormat.
884 * @see setGroupingUsed
887 UBool
isGroupingUsed(void) const;
890 * Set whether or not grouping will be used in this format.
891 * @param newValue True, grouping will be used in this format.
892 * @see getGroupingUsed
895 virtual void setGroupingUsed(UBool newValue
);
898 * Returns the maximum number of digits allowed in the integer portion of a
900 * @return the maximum number of digits allowed in the integer portion of a
902 * @see setMaximumIntegerDigits
905 int32_t getMaximumIntegerDigits(void) const;
908 * Sets the maximum number of digits allowed in the integer portion of a
909 * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
910 * new value for maximumIntegerDigits is less than the current value
911 * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
914 * @param newValue the new value for the maximum number of digits
915 * allowed in the integer portion of a number.
916 * @see getMaximumIntegerDigits
919 virtual void setMaximumIntegerDigits(int32_t newValue
);
922 * Returns the minimum number of digits allowed in the integer portion of a
924 * @return the minimum number of digits allowed in the integer portion of a
926 * @see setMinimumIntegerDigits
929 int32_t getMinimumIntegerDigits(void) const;
932 * Sets the minimum number of digits allowed in the integer portion of a
933 * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the
934 * new value for minimumIntegerDigits exceeds the current value
935 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
937 * @param newValue the new value to be set.
938 * @see getMinimumIntegerDigits
941 virtual void setMinimumIntegerDigits(int32_t newValue
);
944 * Returns the maximum number of digits allowed in the fraction portion of a
946 * @return the maximum number of digits allowed in the fraction portion of a
948 * @see setMaximumFractionDigits
951 int32_t getMaximumFractionDigits(void) const;
954 * Sets the maximum number of digits allowed in the fraction portion of a
955 * number. maximumFractionDigits must be >= minimumFractionDigits. If the
956 * new value for maximumFractionDigits is less than the current value
957 * of minimumFractionDigits, then minimumFractionDigits will also be set to
959 * @param newValue the new value to be set.
960 * @see getMaximumFractionDigits
963 virtual void setMaximumFractionDigits(int32_t newValue
);
966 * Returns the minimum number of digits allowed in the fraction portion of a
968 * @return the minimum number of digits allowed in the fraction portion of a
970 * @see setMinimumFractionDigits
973 int32_t getMinimumFractionDigits(void) const;
976 * Sets the minimum number of digits allowed in the fraction portion of a
977 * number. minimumFractionDigits must be <= maximumFractionDigits. If the
978 * new value for minimumFractionDigits exceeds the current value
979 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
981 * @param newValue the new value to be set.
982 * @see getMinimumFractionDigits
985 virtual void setMinimumFractionDigits(int32_t newValue
);
988 * Sets the currency used to display currency
989 * amounts. This takes effect immediately, if this format is a
990 * currency format. If this format is not a currency format, then
991 * the currency is used if and when this object becomes a
993 * @param theCurrency a 3-letter ISO code indicating new currency
994 * to use. It need not be null-terminated. May be the empty
995 * string or NULL to indicate no currency.
996 * @param ec input-output error code
999 virtual void setCurrency(const char16_t* theCurrency
, UErrorCode
& ec
);
1002 * Gets the currency used to display currency
1003 * amounts. This may be an empty string for some subclasses.
1004 * @return a 3-letter null-terminated ISO code indicating
1005 * the currency in use, or a pointer to the empty string.
1008 const char16_t* getCurrency() const;
1011 * Set a particular UDisplayContext value in the formatter, such as
1012 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
1013 * @param value The UDisplayContext value to set.
1014 * @param status Input/output status. If at entry this indicates a failure
1015 * status, the function will do nothing; otherwise this will be
1016 * updated with any new status from the function.
1019 virtual void setContext(UDisplayContext value
, UErrorCode
& status
);
1022 * Get the formatter's UDisplayContext value for the specified UDisplayContextType,
1023 * such as UDISPCTX_TYPE_CAPITALIZATION.
1024 * @param type The UDisplayContextType whose value to return
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.
1028 * @return The UDisplayContextValue for the specified type.
1031 virtual UDisplayContext
getContext(UDisplayContextType type
, UErrorCode
& status
) const;
1034 * Get the rounding mode. This will always return NumberFormat::ERoundingMode::kRoundUnnecessary
1035 * if the subclass does not support rounding.
1036 * @return A rounding mode
1039 virtual ERoundingMode
getRoundingMode(void) const;
1042 * Set the rounding mode. If a subclass does not support rounding, this will do nothing.
1043 * @param roundingMode A rounding mode
1046 virtual void setRoundingMode(ERoundingMode roundingMode
);
1049 * Group-set several settings used for numbers in date formats.
1051 * setGroupingUsed(FALSE);
1052 * setParseIntegerOnly(TRUE);
1053 * setMinimumFractionDigits(0);
1056 virtual void setDateSettings(void);
1061 * Return the class ID for this class. This is useful for
1062 * comparing to a return value from getDynamicClassID(). Note that,
1063 * because NumberFormat is an abstract base class, no fully constructed object
1064 * will have the class ID returned by NumberFormat::getStaticClassID().
1065 * @return The class ID for all objects of this class.
1068 static UClassID U_EXPORT2
getStaticClassID(void);
1071 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
1072 * This method is to implement a simple version of RTTI, since not all
1073 * C++ compilers support genuine RTTI. Polymorphic operator==() and
1074 * clone() methods call this method.
1076 * @return The class ID for this object. All objects of a
1077 * given class have the same class ID. Objects of
1078 * other classes have different class IDs.
1081 virtual UClassID
getDynamicClassID(void) const = 0;
1086 * Default constructor for subclass use only.
1095 NumberFormat(const NumberFormat
&);
1098 * Assignment operator.
1101 NumberFormat
& operator=(const NumberFormat
&);
1104 * Returns the currency in effect for this formatter. Subclasses
1105 * should override this method as needed. Unlike getCurrency(),
1106 * this method should never return "".
1107 * @result output parameter for null-terminated result, which must
1108 * have a capacity of at least 4
1111 virtual void getEffectiveCurrency(char16_t* result
, UErrorCode
& ec
) const;
1113 #ifndef U_HIDE_INTERNAL_API
1115 * Creates the specified number format style of the desired locale.
1116 * If mustBeDecimalFormat is TRUE, then the returned pointer is
1117 * either a DecimalFormat or it is NULL.
1120 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1121 UNumberFormatStyle style
,
1122 UBool mustBeDecimalFormat
,
1123 UErrorCode
& errorCode
);
1124 #endif /* U_HIDE_INTERNAL_API */
1128 static UBool
isStyleSupported(UNumberFormatStyle style
);
1131 * Creates the specified decimal format style of the desired locale.
1132 * @param desiredLocale the given locale.
1133 * @param style the given style.
1134 * @param errorCode Output param filled with success/failure status.
1135 * @return A new NumberFormat instance.
1137 static NumberFormat
* makeInstance(const Locale
& desiredLocale
,
1138 UNumberFormatStyle style
,
1139 UErrorCode
& errorCode
);
1141 UBool fGroupingUsed
;
1142 int32_t fMaxIntegerDigits
;
1143 int32_t fMinIntegerDigits
;
1144 int32_t fMaxFractionDigits
;
1145 int32_t fMinFractionDigits
;
1149 static const int32_t gDefaultMaxIntegerDigits
;
1151 static const int32_t gDefaultMinIntegerDigits
;
1154 UBool fParseIntegerOnly
;
1155 UBool fLenient
; // TRUE => lenient parse is enabled
1157 // ISO currency code
1158 char16_t fCurrency
[4];
1160 UDisplayContext fCapitalizationContext
;
1162 friend class ICUNumberFormatFactory
; // access to makeInstance
1163 friend class ICUNumberFormatService
;
1164 friend class ::NumberFormatTest
; // access to isStyleSupported()
1167 #if !UCONFIG_NO_SERVICE
1169 * A NumberFormatFactory is used to register new number formats. The factory
1170 * should be able to create any of the predefined formats for each locale it
1171 * supports. When registered, the locales it supports extend or override the
1172 * locale already supported by ICU.
1176 class U_I18N_API NumberFormatFactory
: public UObject
{
1183 virtual ~NumberFormatFactory();
1186 * Return true if this factory will be visible. Default is true.
1187 * If not visible, the locales supported by this factory will not
1188 * be listed by getAvailableLocales.
1191 virtual UBool
visible(void) const = 0;
1194 * Return the locale names directly supported by this factory. The number of names
1195 * is returned in count;
1198 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const = 0;
1201 * Return a number format of the appropriate type. If the locale
1202 * is not supported, return null. If the locale is supported, but
1203 * the type is not provided by this service, return null. Otherwise
1204 * return an appropriate instance of NumberFormat.
1207 virtual NumberFormat
* createFormat(const Locale
& loc
, UNumberFormatStyle formatType
) = 0;
1211 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
1214 class U_I18N_API SimpleNumberFormatFactory
: public NumberFormatFactory
{
1217 * True if the locale supported by this factory is visible.
1220 const UBool _visible
;
1223 * The locale supported by this factory, as a UnicodeString.
1232 SimpleNumberFormatFactory(const Locale
& locale
, UBool visible
= TRUE
);
1237 virtual ~SimpleNumberFormatFactory();
1242 virtual UBool
visible(void) const;
1247 virtual const UnicodeString
* getSupportedIDs(int32_t &count
, UErrorCode
& status
) const;
1249 #endif /* #if !UCONFIG_NO_SERVICE */
1251 // -------------------------------------
1254 NumberFormat::isParseIntegerOnly() const
1256 return fParseIntegerOnly
;
1260 NumberFormat::isLenient() const
1266 #endif // U_SHOW_CPLUSPLUS_API
1268 #endif /* #if !UCONFIG_NO_FORMATTING */