]> git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/unicode/numfmt.h
ICU-64252.0.1.tar.gz
[apple/icu.git] / icuSources / i18n / unicode / numfmt.h
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ********************************************************************************
5 * Copyright (C) 1997-2016, International Business Machines Corporation and others.
6 * All Rights Reserved.
7 ********************************************************************************
8 *
9 * File NUMFMT.H
10 *
11 * Modification History:
12 *
13 * Date Name Description
14 * 02/19/97 aliu Converted from java.
15 * 03/18/97 clhuang Updated per C++ implementation.
16 * 04/17/97 aliu Changed DigitCount to int per code review.
17 * 07/20/98 stephen JDK 1.2 sync up. Added scientific support.
18 * Changed naming conventions to match C++ guidelines
19 * Derecated Java style constants (eg, INTEGER_FIELD)
20 ********************************************************************************
21 */
22
23 #ifndef NUMFMT_H
24 #define NUMFMT_H
25
26
27 #include "unicode/utypes.h"
28
29 /**
30 * \file
31 * \brief C++ API: Compatibility APIs for number formatting.
32 */
33
34 #if !UCONFIG_NO_FORMATTING
35
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"
43
44 class NumberFormatTest;
45
46 #if U_SHOW_CPLUSPLUS_API
47 U_NAMESPACE_BEGIN
48
49 class SharedNumberFormat;
50
51 #if !UCONFIG_NO_SERVICE
52 class NumberFormatFactory;
53 class StringEnumeration;
54 #endif
55
56 /**
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.
60 *
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
64 * are.
65 *
66 * \headerfile unicode/numfmt.h "unicode/numfmt.h"
67 * <P>
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.
72 * <P>
73 * To format a number for the current Locale, use one of the static
74 * factory methods:
75 * \code
76 * #include <iostream>
77 * #include "unicode/numfmt.h"
78 * #include "unicode/unistr.h"
79 * #include "unicode/ustream.h"
80 * using namespace std;
81 *
82 * int main() {
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;
89 * }
90 * \endcode
91 * Note that there are additional factory methods within subclasses of
92 * NumberFormat.
93 * <P>
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.
98 * \code
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);
104 * myString += "; ";
105 * }
106 * cout << " Example 2: " << myString << endl;
107 * \endcode
108 * To format a number for a different Locale, specify it in the
109 * call to \c createInstance().
110 * \code
111 * nf = NumberFormat::createInstance(Locale::getFrench(), success);
112 * \endcode
113 * You can use a \c NumberFormat to parse also.
114 * \code
115 * UErrorCode success;
116 * Formattable result(-999); // initialized with error code
117 * nf->parse(myString, result, success);
118 * \endcode
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%.
124 * <P>
125 * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance().
126 * For example, use\n
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".
137 * <P>
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.
145 * <P>
146 * You can also use forms of the parse and format methods with
147 * \c ParsePosition and \c FieldPosition to allow you to:
148 * <ul type=round>
149 * <li>(a) progressively parse through pieces of a string.
150 * <li>(b) align the decimal point and other areas.
151 * </ul>
152 * For example, you can align numbers in two ways.
153 * <P>
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
159 * string.
160 * <P>
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.
167 * <p>
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.
171 *
172 * @stable ICU 2.0
173 */
174 class U_I18N_API NumberFormat : public Format {
175 public:
176 /**
177 * Rounding mode.
178 *
179 * <p>
180 * For more detail on rounding modes, see:
181 * http://userguide.icu-project.org/formatparse/numbers/rounding-modes
182 *
183 * @stable ICU 2.4
184 */
185 enum ERoundingMode {
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 */
196 /**
197 * Return U_FORMAT_INEXACT_ERROR if number does not format exactly.
198 * @stable ICU 4.8
199 */
200 kRoundUnnecessary
201 };
202
203 /**
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.
207 *
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.
211 *
212 * These constants are provided for backwards compatibility only.
213 * Please use the C style constants defined in the header file unum.h.
214 *
215 * @see FieldPosition
216 * @stable ICU 2.0
217 */
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
242 /** @draft ICU 64 */
243 kMeasureUnitField = UNUM_MEASURE_UNIT_FIELD,
244 /** @draft ICU 64 */
245 kCompactField = UNUM_COMPACT_FIELD,
246 #endif // U_HIDE_DRAFT_API
247
248 /**
249 * These constants are provided for backwards compatibility only.
250 * Please use the constants defined in the header file unum.h.
251 */
252 /** @stable ICU 2.0 */
253 INTEGER_FIELD = UNUM_INTEGER_FIELD,
254 /** @stable ICU 2.0 */
255 FRACTION_FIELD = UNUM_FRACTION_FIELD
256 };
257
258 /**
259 * Destructor.
260 * @stable ICU 2.0
261 */
262 virtual ~NumberFormat();
263
264 /**
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.
268 * @stable ICU 2.0
269 */
270 virtual UBool operator==(const Format& other) const;
271
272
273 using Format::format;
274
275 /**
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
279 * UErrorCode.
280 *
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.
288 * @stable ICU 2.0
289 */
290 virtual UnicodeString& format(const Formattable& obj,
291 UnicodeString& appendTo,
292 FieldPosition& pos,
293 UErrorCode& status) const;
294
295 /**
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
299 * UErrorCode.
300 *
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
306 * NULL.
307 * @param status Output param filled with success/failure status.
308 * @return Reference to 'appendTo' parameter.
309 * @stable ICU 4.4
310 */
311 virtual UnicodeString& format(const Formattable& obj,
312 UnicodeString& appendTo,
313 FieldPositionIterator* posIter,
314 UErrorCode& status) const;
315
316 /**
317 * Parse a string to produce an object. This methods handles
318 * parsing of numeric strings into Formattable objects with numeric
319 * types.
320 * <P>
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.
325 * <P>
326 * When parsing, leading whitespace is discarded (with successful
327 * parse), while trailing whitespace is left as is.
328 * <P>
329 * See Format::parseObject() for more.
330 *
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.
342 * @stable ICU 2.0
343 */
344 virtual void parseObject(const UnicodeString& source,
345 Formattable& result,
346 ParsePosition& parse_pos) const;
347
348 /**
349 * Format a double number. These methods call the NumberFormat
350 * pure virtual format() methods with the default FieldPosition.
351 *
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.
356 * @stable ICU 2.0
357 */
358 UnicodeString& format( double number,
359 UnicodeString& appendTo) const;
360
361 /**
362 * Format a long number. These methods call the NumberFormat
363 * pure virtual format() methods with the default FieldPosition.
364 *
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.
369 * @stable ICU 2.0
370 */
371 UnicodeString& format( int32_t number,
372 UnicodeString& appendTo) const;
373
374 /**
375 * Format an int64 number. These methods call the NumberFormat
376 * pure virtual format() methods with the default FieldPosition.
377 *
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.
382 * @stable ICU 2.8
383 */
384 UnicodeString& format( int64_t number,
385 UnicodeString& appendTo) const;
386
387 /**
388 * Format a double number. Concrete subclasses must implement
389 * these pure virtual methods.
390 *
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.
397 * @stable ICU 2.0
398 */
399 virtual UnicodeString& format(double number,
400 UnicodeString& appendTo,
401 FieldPosition& pos) const = 0;
402 /**
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.
406 *
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.
414 * @internal
415 */
416 virtual UnicodeString& format(double number,
417 UnicodeString& appendTo,
418 FieldPosition& pos,
419 UErrorCode &status) const;
420 /**
421 * Format a double number. Subclasses must implement
422 * this method.
423 *
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.
429 * Can be NULL.
430 * @param status Output param filled with success/failure status.
431 * @return Reference to 'appendTo' parameter.
432 * @stable ICU 4.4
433 */
434 virtual UnicodeString& format(double number,
435 UnicodeString& appendTo,
436 FieldPositionIterator* posIter,
437 UErrorCode& status) const;
438 /**
439 * Format a long number. Concrete subclasses must implement
440 * these pure virtual methods.
441 *
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.
448 * @stable ICU 2.0
449 */
450 virtual UnicodeString& format(int32_t number,
451 UnicodeString& appendTo,
452 FieldPosition& pos) const = 0;
453
454 /**
455 * Format a long number. Concrete subclasses may override
456 * this function to provide status return.
457 *
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.
465 * @internal
466 */
467 virtual UnicodeString& format(int32_t number,
468 UnicodeString& appendTo,
469 FieldPosition& pos,
470 UErrorCode &status) const;
471
472 /**
473 * Format an int32 number. Subclasses must implement
474 * this method.
475 *
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.
481 * Can be NULL.
482 * @param status Output param filled with success/failure status.
483 * @return Reference to 'appendTo' parameter.
484 * @stable ICU 4.4
485 */
486 virtual UnicodeString& format(int32_t number,
487 UnicodeString& appendTo,
488 FieldPositionIterator* posIter,
489 UErrorCode& status) const;
490 /**
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...);
494 *
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.
501 * @stable ICU 2.8
502 */
503 virtual UnicodeString& format(int64_t number,
504 UnicodeString& appendTo,
505 FieldPosition& pos) const;
506
507 /**
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...);
511 *
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.
519 * @internal
520 */
521 virtual UnicodeString& format(int64_t number,
522 UnicodeString& appendTo,
523 FieldPosition& pos,
524 UErrorCode& status) const;
525 /**
526 * Format an int64 number. Subclasses must implement
527 * this method.
528 *
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.
534 * Can be NULL.
535 * @param status Output param filled with success/failure status.
536 * @return Reference to 'appendTo' parameter.
537 * @stable ICU 4.4
538 */
539 virtual UnicodeString& format(int64_t number,
540 UnicodeString& appendTo,
541 FieldPositionIterator* posIter,
542 UErrorCode& status) const;
543
544 /**
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
549 *
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.
555 * Can be NULL.
556 * @param status Output param filled with success/failure status.
557 * @return Reference to 'appendTo' parameter.
558 * @stable ICU 4.4
559 */
560 virtual UnicodeString& format(StringPiece number,
561 UnicodeString& appendTo,
562 FieldPositionIterator* posIter,
563 UErrorCode& status) const;
564
565 // Can't use #ifndef U_HIDE_INTERNAL_API because these are virtual methods
566
567 /**
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.
574 *
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.
582 * @internal
583 */
584 virtual UnicodeString& format(const number::impl::DecimalQuantity &number,
585 UnicodeString& appendTo,
586 FieldPositionIterator* posIter,
587 UErrorCode& status) const;
588
589 /**
590 * Format a decimal number.
591 * The number is a DecimalQuantity wrapper onto a floating point decimal number.
592 * The default implementation in NumberFormat converts the decimal number
593 * to a double and formats that. Subclasses of NumberFormat that want
594 * to specifically handle big decimal numbers must override this method.
595 * class DecimalFormat does so.
596 *
597 * @param number The number, a DecimalQuantity format Decimal Floating Point.
598 * @param appendTo Output parameter to receive result.
599 * Result is appended to existing contents.
600 * @param 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.
604 * @internal
605 */
606 virtual UnicodeString& format(const number::impl::DecimalQuantity &number,
607 UnicodeString& appendTo,
608 FieldPosition& pos,
609 UErrorCode& status) const;
610
611 /**
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).
616 * <P>
617 * If no object can be parsed, index is unchanged, and NULL is
618 * returned.
619 * <P>
620 * This is a pure virtual which concrete subclasses must implement.
621 *
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.
628 * @stable ICU 2.0
629 */
630 virtual void parse(const UnicodeString& text,
631 Formattable& result,
632 ParsePosition& parsePosition) const = 0;
633
634 /**
635 * Parse a string as a numeric value, and return a Formattable
636 * numeric object. This method parses integers only if IntegerOnly
637 * is set.
638 *
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
645 * @stable ICU 2.0
646 */
647 virtual void parse(const UnicodeString& text,
648 Formattable& result,
649 UErrorCode& status) const;
650
651 /**
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.
659 *
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.
668 * @stable ICU 49
669 */
670 virtual CurrencyAmount* parseCurrency(const UnicodeString& text,
671 ParsePosition& pos) const;
672
673 /**
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
681 * only.
682 * @stable ICU 2.0
683 */
684 UBool isParseIntegerOnly(void) const;
685
686 /**
687 * Sets whether or not numbers should be parsed as integers only.
688 * @param value set True, this format will parse numbers as integers
689 * only.
690 * @see isParseIntegerOnly
691 * @stable ICU 2.0
692 */
693 virtual void setParseIntegerOnly(UBool value);
694
695 /**
696 * Sets whether lenient parsing should be enabled (it is off by default).
697 *
698 * @param enable \c TRUE if lenient parsing should be used,
699 * \c FALSE otherwise.
700 * @stable ICU 4.8
701 */
702 virtual void setLenient(UBool enable);
703
704 /**
705 * Returns whether lenient parsing is enabled (it is off by default).
706 *
707 * @return \c TRUE if lenient parsing is enabled,
708 * \c FALSE otherwise.
709 * @see #setLenient
710 * @stable ICU 4.8
711 */
712 virtual UBool isLenient(void) const;
713
714 /**
715 * Create a default style NumberFormat for the current default locale.
716 * The default formatting style is locale dependent.
717 * <p>
718 * <strong>NOTE:</strong> New users are strongly encouraged to use
719 * {@link icu::number::NumberFormatter} instead of NumberFormat.
720 * @stable ICU 2.0
721 */
722 static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
723
724 /**
725 * Create a default style NumberFormat for the specified locale.
726 * The default formatting style is locale dependent.
727 * @param inLocale the given locale.
728 * <p>
729 * <strong>NOTE:</strong> New users are strongly encouraged to use
730 * {@link icu::number::NumberFormatter} instead of NumberFormat.
731 * @stable ICU 2.0
732 */
733 static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
734 UErrorCode&);
735
736 /**
737 * Create a specific style NumberFormat for the specified locale.
738 * <p>
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.
745 * @stable ICU 4.8
746 */
747 static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale,
748 UNumberFormatStyle style,
749 UErrorCode& errorCode);
750
751 #ifndef U_HIDE_INTERNAL_API
752
753 /**
754 * ICU use only.
755 * Creates NumberFormat instance without using the cache.
756 * @internal
757 */
758 static NumberFormat* internalCreateInstance(
759 const Locale& desiredLocale,
760 UNumberFormatStyle style,
761 UErrorCode& errorCode);
762
763 /**
764 * ICU use only.
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.
768 * @internal
769 */
770 static const SharedNumberFormat* U_EXPORT2 createSharedInstance(
771 const Locale& inLocale, UNumberFormatStyle style, UErrorCode& status);
772
773 #endif /* U_HIDE_INTERNAL_API */
774
775 /**
776 * Returns a currency format for the current default locale.
777 * <p>
778 * <strong>NOTE:</strong> New users are strongly encouraged to use
779 * {@link icu::number::NumberFormatter} instead of NumberFormat.
780 * @stable ICU 2.0
781 */
782 static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
783
784 /**
785 * Returns a currency format for the specified locale.
786 * <p>
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.
790 * @stable ICU 2.0
791 */
792 static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
793 UErrorCode&);
794
795 /**
796 * Returns a percentage format for the current default locale.
797 * <p>
798 * <strong>NOTE:</strong> New users are strongly encouraged to use
799 * {@link icu::number::NumberFormatter} instead of NumberFormat.
800 * @stable ICU 2.0
801 */
802 static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
803
804 /**
805 * Returns a percentage format for the specified locale.
806 * <p>
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.
810 * @stable ICU 2.0
811 */
812 static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
813 UErrorCode&);
814
815 /**
816 * Returns a scientific format for the current default locale.
817 * <p>
818 * <strong>NOTE:</strong> New users are strongly encouraged to use
819 * {@link icu::number::NumberFormatter} instead of NumberFormat.
820 * @stable ICU 2.0
821 */
822 static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
823
824 /**
825 * Returns a scientific format for the specified locale.
826 * <p>
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.
830 * @stable ICU 2.0
831 */
832 static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
833 UErrorCode&);
834
835 /**
836 * Get the set of Locales for which NumberFormats are installed.
837 * @param count Output param to receive the size of the locales
838 * @stable ICU 2.0
839 */
840 static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
841
842 #if !UCONFIG_NO_SERVICE
843 /**
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
851 * @stable ICU 2.6
852 */
853 static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
854
855 /**
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
865 * @stable ICU 2.6
866 */
867 static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
868
869 /**
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
873 * @stable ICU 2.6
874 */
875 static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
876 #endif /* UCONFIG_NO_SERVICE */
877
878 /**
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
885 * @stable ICU 2.0
886 */
887 UBool isGroupingUsed(void) const;
888
889 /**
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
893 * @stable ICU 2.0
894 */
895 virtual void setGroupingUsed(UBool newValue);
896
897 /**
898 * Returns the maximum number of digits allowed in the integer portion of a
899 * number.
900 * @return the maximum number of digits allowed in the integer portion of a
901 * number.
902 * @see setMaximumIntegerDigits
903 * @stable ICU 2.0
904 */
905 int32_t getMaximumIntegerDigits(void) const;
906
907 /**
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
912 * the new value.
913 *
914 * @param newValue the new value for the maximum number of digits
915 * allowed in the integer portion of a number.
916 * @see getMaximumIntegerDigits
917 * @stable ICU 2.0
918 */
919 virtual void setMaximumIntegerDigits(int32_t newValue);
920
921 /**
922 * Returns the minimum number of digits allowed in the integer portion of a
923 * number.
924 * @return the minimum number of digits allowed in the integer portion of a
925 * number.
926 * @see setMinimumIntegerDigits
927 * @stable ICU 2.0
928 */
929 int32_t getMinimumIntegerDigits(void) const;
930
931 /**
932 * Sets the minimum number of digits allowed in the integer portion of a
933 * number. minimumIntegerDigits must be &lt;= maximumIntegerDigits. If the
934 * new value for minimumIntegerDigits exceeds the current value
935 * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
936 * the new value.
937 * @param newValue the new value to be set.
938 * @see getMinimumIntegerDigits
939 * @stable ICU 2.0
940 */
941 virtual void setMinimumIntegerDigits(int32_t newValue);
942
943 /**
944 * Returns the maximum number of digits allowed in the fraction portion of a
945 * number.
946 * @return the maximum number of digits allowed in the fraction portion of a
947 * number.
948 * @see setMaximumFractionDigits
949 * @stable ICU 2.0
950 */
951 int32_t getMaximumFractionDigits(void) const;
952
953 /**
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
958 * the new value.
959 * @param newValue the new value to be set.
960 * @see getMaximumFractionDigits
961 * @stable ICU 2.0
962 */
963 virtual void setMaximumFractionDigits(int32_t newValue);
964
965 /**
966 * Returns the minimum number of digits allowed in the fraction portion of a
967 * number.
968 * @return the minimum number of digits allowed in the fraction portion of a
969 * number.
970 * @see setMinimumFractionDigits
971 * @stable ICU 2.0
972 */
973 int32_t getMinimumFractionDigits(void) const;
974
975 /**
976 * Sets the minimum number of digits allowed in the fraction portion of a
977 * number. minimumFractionDigits must be &lt;= maximumFractionDigits. If the
978 * new value for minimumFractionDigits exceeds the current value
979 * of maximumFractionDigits, then maximumIntegerDigits will also be set to
980 * the new value
981 * @param newValue the new value to be set.
982 * @see getMinimumFractionDigits
983 * @stable ICU 2.0
984 */
985 virtual void setMinimumFractionDigits(int32_t newValue);
986
987 /**
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
992 * currency format.
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
997 * @stable ICU 3.0
998 */
999 virtual void setCurrency(const char16_t* theCurrency, UErrorCode& ec);
1000
1001 /**
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.
1006 * @stable ICU 2.6
1007 */
1008 const char16_t* getCurrency() const;
1009
1010 /**
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.
1017 * @stable ICU 53
1018 */
1019 virtual void setContext(UDisplayContext value, UErrorCode& status);
1020
1021 /**
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.
1029 * @stable ICU 53
1030 */
1031 virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const;
1032
1033 /**
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
1037 * @stable ICU 60
1038 */
1039 virtual ERoundingMode getRoundingMode(void) const;
1040
1041 /**
1042 * Set the rounding mode. If a subclass does not support rounding, this will do nothing.
1043 * @param roundingMode A rounding mode
1044 * @stable ICU 60
1045 */
1046 virtual void setRoundingMode(ERoundingMode roundingMode);
1047
1048 /**
1049 * Group-set several settings used for numbers in date formats.
1050 * Equivalent to:
1051 * setGroupingUsed(FALSE);
1052 * setParseIntegerOnly(TRUE);
1053 * setMinimumFractionDigits(0);
1054 * @internal
1055 */
1056 virtual void setDateSettings(void);
1057
1058 public:
1059
1060 /**
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.
1066 * @stable ICU 2.0
1067 */
1068 static UClassID U_EXPORT2 getStaticClassID(void);
1069
1070 /**
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.
1075 * <P>
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.
1079 * @stable ICU 2.0
1080 */
1081 virtual UClassID getDynamicClassID(void) const = 0;
1082
1083 protected:
1084
1085 /**
1086 * Default constructor for subclass use only.
1087 * @stable ICU 2.0
1088 */
1089 NumberFormat();
1090
1091 /**
1092 * Copy constructor.
1093 * @stable ICU 2.0
1094 */
1095 NumberFormat(const NumberFormat&);
1096
1097 /**
1098 * Assignment operator.
1099 * @stable ICU 2.0
1100 */
1101 NumberFormat& operator=(const NumberFormat&);
1102
1103 /**
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
1109 * @internal
1110 */
1111 virtual void getEffectiveCurrency(char16_t* result, UErrorCode& ec) const;
1112
1113 #ifndef U_HIDE_INTERNAL_API
1114 /**
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.
1118 * @internal
1119 */
1120 static NumberFormat* makeInstance(const Locale& desiredLocale,
1121 UNumberFormatStyle style,
1122 UBool mustBeDecimalFormat,
1123 UErrorCode& errorCode);
1124 #endif /* U_HIDE_INTERNAL_API */
1125
1126 private:
1127
1128 static UBool isStyleSupported(UNumberFormatStyle style);
1129
1130 /**
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.
1136 */
1137 static NumberFormat* makeInstance(const Locale& desiredLocale,
1138 UNumberFormatStyle style,
1139 UErrorCode& errorCode);
1140
1141 UBool fGroupingUsed;
1142 int32_t fMaxIntegerDigits;
1143 int32_t fMinIntegerDigits;
1144 int32_t fMaxFractionDigits;
1145 int32_t fMinFractionDigits;
1146
1147 protected:
1148 /** \internal */
1149 static const int32_t gDefaultMaxIntegerDigits;
1150 /** \internal */
1151 static const int32_t gDefaultMinIntegerDigits;
1152
1153 private:
1154 UBool fParseIntegerOnly;
1155 UBool fLenient; // TRUE => lenient parse is enabled
1156
1157 // ISO currency code
1158 char16_t fCurrency[4];
1159
1160 UDisplayContext fCapitalizationContext;
1161
1162 friend class ICUNumberFormatFactory; // access to makeInstance
1163 friend class ICUNumberFormatService;
1164 friend class ::NumberFormatTest; // access to isStyleSupported()
1165 };
1166
1167 #if !UCONFIG_NO_SERVICE
1168 /**
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.
1173 *
1174 * @stable ICU 2.6
1175 */
1176 class U_I18N_API NumberFormatFactory : public UObject {
1177 public:
1178
1179 /**
1180 * Destructor
1181 * @stable ICU 3.0
1182 */
1183 virtual ~NumberFormatFactory();
1184
1185 /**
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.
1189 * @stable ICU 2.6
1190 */
1191 virtual UBool visible(void) const = 0;
1192
1193 /**
1194 * Return the locale names directly supported by this factory. The number of names
1195 * is returned in count;
1196 * @stable ICU 2.6
1197 */
1198 virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0;
1199
1200 /**
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.
1205 * @stable ICU 2.6
1206 */
1207 virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0;
1208 };
1209
1210 /**
1211 * A NumberFormatFactory that supports a single locale. It can be visible or invisible.
1212 * @stable ICU 2.6
1213 */
1214 class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory {
1215 protected:
1216 /**
1217 * True if the locale supported by this factory is visible.
1218 * @stable ICU 2.6
1219 */
1220 const UBool _visible;
1221
1222 /**
1223 * The locale supported by this factory, as a UnicodeString.
1224 * @stable ICU 2.6
1225 */
1226 UnicodeString _id;
1227
1228 public:
1229 /**
1230 * @stable ICU 2.6
1231 */
1232 SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE);
1233
1234 /**
1235 * @stable ICU 3.0
1236 */
1237 virtual ~SimpleNumberFormatFactory();
1238
1239 /**
1240 * @stable ICU 2.6
1241 */
1242 virtual UBool visible(void) const;
1243
1244 /**
1245 * @stable ICU 2.6
1246 */
1247 virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const;
1248 };
1249 #endif /* #if !UCONFIG_NO_SERVICE */
1250
1251 // -------------------------------------
1252
1253 inline UBool
1254 NumberFormat::isParseIntegerOnly() const
1255 {
1256 return fParseIntegerOnly;
1257 }
1258
1259 inline UBool
1260 NumberFormat::isLenient() const
1261 {
1262 return fLenient;
1263 }
1264
1265 U_NAMESPACE_END
1266 #endif // U_SHOW_CPLUSPLUS_API
1267
1268 #endif /* #if !UCONFIG_NO_FORMATTING */
1269
1270 #endif // _NUMFMT
1271 //eof