1 // © 2018 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 #include "unicode/utypes.h"
6 #if !UCONFIG_NO_FORMATTING
7 #ifndef __UNUMBERFORMATTER_H__
8 #define __UNUMBERFORMATTER_H__
10 #include "unicode/parseerr.h"
11 #include "unicode/ufieldpositer.h"
12 #include "unicode/umisc.h"
13 #include "unicode/uformattedvalue.h"
18 * \brief C-compatible API for localized number formatting; not recommended for C++.
20 * This is the C-compatible version of the NumberFormatter API introduced in ICU 60. C++ users should
21 * include unicode/numberformatter.h and use the proper C++ APIs.
23 * The C API accepts a number skeleton string for specifying the settings for formatting, which covers a
24 * very large subset of all possible number formatting features. For more information on number skeleton
25 * strings, see unicode/numberformatter.h.
27 * When using UNumberFormatter, which is treated as immutable, the results are exported to a mutable
28 * UFormattedNumber object, which you subsequently use for populating your string buffer or iterating over
34 * UErrorCode ec = U_ZERO_ERROR;
35 * UNumberFormatter* uformatter = unumf_openForSkeletonAndLocale(u"precision-integer", -1, "en", &ec);
36 * UFormattedNumber* uresult = unumf_openResult(&ec);
37 * if (U_FAILURE(ec)) { return; }
40 * unumf_formatDouble(uformatter, 5142.3, uresult, &ec);
41 * if (U_FAILURE(ec)) { return; }
43 * // Export the string to a malloc'd buffer:
44 * int32_t len = unumf_resultToString(uresult, NULL, 0, &ec);
45 * // at this point, ec == U_BUFFER_OVERFLOW_ERROR
47 * UChar* buffer = (UChar*) malloc((len+1)*sizeof(UChar));
48 * unumf_resultToString(uresult, buffer, len+1, &ec);
49 * if (U_FAILURE(ec)) { return; }
50 * // buffer should equal "5,142"
53 * unumf_close(uformatter);
54 * unumf_closeResult(uresult);
58 * If you are a C++ user linking against the C libraries, you can use the LocalPointer versions of these
59 * APIs. The following example uses LocalPointer with the decimal number and field position APIs:
63 * LocalUNumberFormatterPointer uformatter(unumf_openForSkeletonAndLocale(u"percent", -1, "en", &ec));
64 * LocalUFormattedNumberPointer uresult(unumf_openResult(&ec));
65 * if (U_FAILURE(ec)) { return; }
67 * // Format a decimal number:
68 * unumf_formatDecimal(uformatter.getAlias(), "9.87E-3", -1, uresult.getAlias(), &ec);
69 * if (U_FAILURE(ec)) { return; }
71 * // Get the location of the percent sign:
72 * UFieldPosition ufpos = {UNUM_PERCENT_FIELD, 0, 0};
73 * unumf_resultNextFieldPosition(uresult.getAlias(), &ufpos, &ec);
74 * // ufpos should contain beginIndex=7 and endIndex=8 since the string is "0.00987%"
76 * // No need to do any cleanup since we are using LocalPointer.
81 #ifndef U_HIDE_DRAFT_API
83 * An enum declaring how to render units, including currencies. Example outputs when formatting 123 USD and 123
84 * meters in <em>en-CA</em>:
88 * <li>NARROW*: "$123.00" and "123 m"
89 * <li>SHORT: "US$ 123.00" and "123 m"
90 * <li>FULL_NAME: "123.00 US dollars" and "123 meters"
91 * <li>ISO_CODE: "USD 123.00" and undefined behavior
92 * <li>HIDDEN: "123.00" and "123"
96 * This enum is similar to {@link UMeasureFormatWidth}.
100 typedef enum UNumberUnitWidth
{
102 * Print an abbreviated version of the unit name. Similar to SHORT, but always use the shortest available
103 * abbreviation or symbol. This option can be used when the context hints at the identity of the unit. For more
104 * information on the difference between NARROW and SHORT, see SHORT.
107 * In CLDR, this option corresponds to the "Narrow" format for measure units and the "¤¤¤¤¤" placeholder for
112 UNUM_UNIT_WIDTH_NARROW
,
115 * Print an abbreviated version of the unit name. Similar to NARROW, but use a slightly wider abbreviation or
116 * symbol when there may be ambiguity. This is the default behavior.
119 * For example, in <em>es-US</em>, the SHORT form for Fahrenheit is "{0} °F", but the NARROW form is "{0}°",
120 * since Fahrenheit is the customary unit for temperature in that locale.
123 * In CLDR, this option corresponds to the "Short" format for measure units and the "¤" placeholder for
128 UNUM_UNIT_WIDTH_SHORT
,
131 * Print the full name of the unit, without any abbreviations.
134 * In CLDR, this option corresponds to the default format for measure units and the "¤¤¤" placeholder for
139 UNUM_UNIT_WIDTH_FULL_NAME
,
142 * Use the three-digit ISO XXX code in place of the symbol for displaying currencies. The behavior of this
143 * option is currently undefined for use with measure units.
146 * In CLDR, this option corresponds to the "¤¤" placeholder for currencies.
150 UNUM_UNIT_WIDTH_ISO_CODE
,
153 * Format the number according to the specified unit, but do not display the unit. For currencies, apply
154 * monetary symbols and formats as with SHORT, but omit the currency symbol. For measure units, the behavior is
155 * equivalent to not specifying the unit at all.
159 UNUM_UNIT_WIDTH_HIDDEN
,
162 * One more than the highest UNumberUnitWidth value.
164 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
166 UNUM_UNIT_WIDTH_COUNT
168 #endif /* U_HIDE_DRAFT_API */
170 #ifndef U_HIDE_DRAFT_API
172 * An enum declaring the strategy for when and how to display grouping separators (i.e., the
173 * separator, often a comma or period, after every 2-3 powers of ten). The choices are several
174 * pre-built strategies for different use cases that employ locale data whenever possible. Example
175 * outputs for 1234 and 1234567 in <em>en-IN</em>:
178 * <li>OFF: 1234 and 12345
179 * <li>MIN2: 1234 and 12,34,567
180 * <li>AUTO: 1,234 and 12,34,567
181 * <li>ON_ALIGNED: 1,234 and 12,34,567
182 * <li>THOUSANDS: 1,234 and 1,234,567
186 * The default is AUTO, which displays grouping separators unless the locale data says that grouping
187 * is not customary. To force grouping for all numbers greater than 1000 consistently across locales,
188 * use ON_ALIGNED. On the other hand, to display grouping less frequently than the default, use MIN2
189 * or OFF. See the docs of each option for details.
192 * Note: This enum specifies the strategy for grouping sizes. To set which character to use as the
193 * grouping separator, use the "symbols" setter.
197 typedef enum UNumberGroupingStrategy
{
199 * Do not display grouping separators in any locale.
206 * Display grouping using locale defaults, except do not show grouping on values smaller than
207 * 10000 (such that there is a <em>minimum of two digits</em> before the first separator).
210 * Note that locales may restrict grouping separators to be displayed only on 1 million or
211 * greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
214 * Locale data is used to determine whether to separate larger numbers into groups of 2
215 * (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
222 * Display grouping using the default strategy for all locales. This is the default behavior.
225 * Note that locales may restrict grouping separators to be displayed only on 1 million or
226 * greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
229 * Locale data is used to determine whether to separate larger numbers into groups of 2
230 * (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
237 * Always display the grouping separator on values of at least 1000.
240 * This option ignores the locale data that restricts or disables grouping, described in MIN2 and
241 * AUTO. This option may be useful to normalize the alignment of numbers, such as in a
245 * Locale data is used to determine whether to separate larger numbers into groups of 2
246 * (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
250 UNUM_GROUPING_ON_ALIGNED
,
253 * Use the Western defaults: groups of 3 and enabled for all numbers 1000 or greater. Do not use
254 * locale data for determining the grouping strategy.
258 UNUM_GROUPING_THOUSANDS
260 #ifndef U_HIDE_INTERNAL_API
263 * One more than the highest UNumberGroupingStrategy value.
265 * @internal ICU 62: The numeric value may change over time; see ICU ticket #12420.
268 #endif /* U_HIDE_INTERNAL_API */
270 } UNumberGroupingStrategy
;
273 #endif /* U_HIDE_DRAFT_API */
275 #ifndef U_HIDE_DRAFT_API
277 * An enum declaring how to denote positive and negative numbers. Example outputs when formatting
278 * 123, 0, and -123 in <em>en-US</em>:
281 * <li>AUTO: "123", "0", and "-123"
282 * <li>ALWAYS: "+123", "+0", and "-123"
283 * <li>NEVER: "123", "0", and "123"
284 * <li>ACCOUNTING: "$123", "$0", and "($123)"
285 * <li>ACCOUNTING_ALWAYS: "+$123", "+$0", and "($123)"
286 * <li>EXCEPT_ZERO: "+123", "0", and "-123"
287 * <li>ACCOUNTING_EXCEPT_ZERO: "+$123", "$0", and "($123)"
291 * The exact format, including the position and the code point of the sign, differ by locale.
295 typedef enum UNumberSignDisplay
{
297 * Show the minus sign on negative numbers, and do not show the sign on positive numbers. This is the default
305 * Show the minus sign on negative numbers and the plus sign on positive numbers, including zero.
306 * To hide the sign on zero, see {@link UNUM_SIGN_EXCEPT_ZERO}.
313 * Do not show the sign on positive or negative numbers.
320 * Use the locale-dependent accounting format on negative numbers, and do not show the sign on positive numbers.
323 * The accounting format is defined in CLDR and varies by locale; in many Western locales, the format is a pair
324 * of parentheses around the number.
327 * Note: Since CLDR defines the accounting format in the monetary context only, this option falls back to the
328 * AUTO sign display strategy when formatting without a currency unit. This limitation may be lifted in the
333 UNUM_SIGN_ACCOUNTING
,
336 * Use the locale-dependent accounting format on negative numbers, and show the plus sign on
337 * positive numbers, including zero. For more information on the accounting format, see the
338 * ACCOUNTING sign display strategy. To hide the sign on zero, see
339 * {@link UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO}.
343 UNUM_SIGN_ACCOUNTING_ALWAYS
,
346 * Show the minus sign on negative numbers and the plus sign on positive numbers. Do not show a
351 UNUM_SIGN_EXCEPT_ZERO
,
354 * Use the locale-dependent accounting format on negative numbers, and show the plus sign on
355 * positive numbers. Do not show a sign on zero. For more information on the accounting format,
356 * see the ACCOUNTING sign display strategy.
360 UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO
,
363 * One more than the highest UNumberSignDisplay value.
365 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
368 } UNumberSignDisplay
;
369 #endif /* U_HIDE_DRAFT_API */
371 #ifndef U_HIDE_DRAFT_API
373 * An enum declaring how to render the decimal separator.
377 * <li>UNUM_DECIMAL_SEPARATOR_AUTO: "1", "1.1"
378 * <li>UNUM_DECIMAL_SEPARATOR_ALWAYS: "1.", "1.1"
383 typedef enum UNumberDecimalSeparatorDisplay
{
385 * Show the decimal separator when there are one or more digits to display after the separator, and do not show
386 * it otherwise. This is the default behavior.
390 UNUM_DECIMAL_SEPARATOR_AUTO
,
393 * Always show the decimal separator, even if there are no digits to display after the separator.
397 UNUM_DECIMAL_SEPARATOR_ALWAYS
,
400 * One more than the highest UNumberDecimalSeparatorDisplay value.
402 * @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
404 UNUM_DECIMAL_SEPARATOR_COUNT
405 } UNumberDecimalSeparatorDisplay
;
406 #endif /* U_HIDE_DRAFT_API */
408 struct UNumberFormatter
;
410 * C-compatible version of icu::number::LocalizedNumberFormatter.
412 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
416 typedef struct UNumberFormatter UNumberFormatter
;
418 struct UFormattedNumber
;
420 * C-compatible version of icu::number::FormattedNumber.
422 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
426 typedef struct UFormattedNumber UFormattedNumber
;
430 * Creates a new UNumberFormatter for the given skeleton string and locale. This is currently the only
431 * method for creating a new UNumberFormatter.
433 * Objects of type UNumberFormatter returned by this method are threadsafe.
435 * For more details on skeleton strings, see the documentation in numberformatter.h. For more details on
436 * the usage of this API, see the documentation at the top of unumberformatter.h.
438 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
440 * @param skeleton The skeleton string, like u"percent precision-integer"
441 * @param skeletonLen The number of UChars in the skeleton string, or -1 it it is NUL-terminated.
442 * @param locale The NUL-terminated locale ID.
443 * @param ec Set if an error occurs.
446 U_STABLE UNumberFormatter
* U_EXPORT2
447 unumf_openForSkeletonAndLocale(const UChar
* skeleton
, int32_t skeletonLen
, const char* locale
,
451 #ifndef U_HIDE_DRAFT_API
453 * Like unumf_openForSkeletonAndLocale, but accepts a UParseError, which will be populated with the
454 * location of a skeleton syntax error if such a syntax error exists.
456 * @param skeleton The skeleton string, like u"percent precision-integer"
457 * @param skeletonLen The number of UChars in the skeleton string, or -1 it it is NUL-terminated.
458 * @param locale The NUL-terminated locale ID.
459 * @param perror A parse error struct populated if an error occurs when parsing. Can be NULL.
460 * If no error occurs, perror->offset will be set to -1.
461 * @param ec Set if an error occurs.
464 U_DRAFT UNumberFormatter
* U_EXPORT2
465 unumf_openForSkeletonAndLocaleWithError(
466 const UChar
* skeleton
, int32_t skeletonLen
, const char* locale
, UParseError
* perror
, UErrorCode
* ec
);
467 #endif // U_HIDE_DRAFT_API
471 * Creates an object to hold the result of a UNumberFormatter
472 * operation. The object can be used repeatedly; it is cleared whenever
473 * passed to a format function.
475 * @param ec Set if an error occurs.
478 U_STABLE UFormattedNumber
* U_EXPORT2
479 unumf_openResult(UErrorCode
* ec
);
483 * Uses a UNumberFormatter to format an integer to a UFormattedNumber. A string, field position, and other
484 * information can be retrieved from the UFormattedNumber.
486 * The UNumberFormatter can be shared between threads. Each thread should have its own local
487 * UFormattedNumber, however, for storing the result of the formatting operation.
489 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
491 * @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
492 * @param value The number to be formatted.
493 * @param uresult The object that will be mutated to store the result; see unumf_openResult.
494 * @param ec Set if an error occurs.
497 U_STABLE
void U_EXPORT2
498 unumf_formatInt(const UNumberFormatter
* uformatter
, int64_t value
, UFormattedNumber
* uresult
,
503 * Uses a UNumberFormatter to format a double to a UFormattedNumber. A string, field position, and other
504 * information can be retrieved from the UFormattedNumber.
506 * The UNumberFormatter can be shared between threads. Each thread should have its own local
507 * UFormattedNumber, however, for storing the result of the formatting operation.
509 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
511 * @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
512 * @param value The number to be formatted.
513 * @param uresult The object that will be mutated to store the result; see unumf_openResult.
514 * @param ec Set if an error occurs.
517 U_STABLE
void U_EXPORT2
518 unumf_formatDouble(const UNumberFormatter
* uformatter
, double value
, UFormattedNumber
* uresult
,
523 * Uses a UNumberFormatter to format a decimal number to a UFormattedNumber. A string, field position, and
524 * other information can be retrieved from the UFormattedNumber.
526 * The UNumberFormatter can be shared between threads. Each thread should have its own local
527 * UFormattedNumber, however, for storing the result of the formatting operation.
529 * The syntax of the unformatted number is a "numeric string" as defined in the Decimal Arithmetic
530 * Specification, available at http://speleotrove.com/decimal
532 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
534 * @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
535 * @param value The numeric string to be formatted.
536 * @param valueLen The length of the numeric string, or -1 if it is NUL-terminated.
537 * @param uresult The object that will be mutated to store the result; see unumf_openResult.
538 * @param ec Set if an error occurs.
541 U_STABLE
void U_EXPORT2
542 unumf_formatDecimal(const UNumberFormatter
* uformatter
, const char* value
, int32_t valueLen
,
543 UFormattedNumber
* uresult
, UErrorCode
* ec
);
545 #ifndef U_HIDE_DRAFT_API
547 * Returns a representation of a UFormattedNumber as a UFormattedValue,
548 * which can be subsequently passed to any API requiring that type.
550 * The returned object is owned by the UFormattedNumber and is valid
551 * only as long as the UFormattedNumber is present and unchanged in memory.
553 * You can think of this method as a cast between types.
555 * @param uresult The object containing the formatted string.
556 * @param ec Set if an error occurs.
557 * @return A UFormattedValue owned by the input object.
560 U_DRAFT
const UFormattedValue
* U_EXPORT2
561 unumf_resultAsValue(const UFormattedNumber
* uresult
, UErrorCode
* ec
);
562 #endif /* U_HIDE_DRAFT_API */
566 * Extracts the result number string out of a UFormattedNumber to a UChar buffer if possible.
567 * If bufferCapacity is greater than the required length, a terminating NUL is written.
568 * If bufferCapacity is less than the required length, an error code is set.
570 * Also see ufmtval_getString, which returns a NUL-terminated string:
573 * const UChar* str = ufmtval_getString(unumf_resultAsValue(uresult, &ec), &len, &ec);
575 * NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
577 * @param uresult The object containing the formatted number.
578 * @param buffer Where to save the string output.
579 * @param bufferCapacity The number of UChars available in the buffer.
580 * @param ec Set if an error occurs.
581 * @return The required length.
584 U_STABLE
int32_t U_EXPORT2
585 unumf_resultToString(const UFormattedNumber
* uresult
, UChar
* buffer
, int32_t bufferCapacity
,
590 * Determines the start and end indices of the next occurrence of the given <em>field</em> in the
591 * output string. This allows you to determine the locations of, for example, the integer part,
592 * fraction part, or symbols.
594 * This is a simpler but less powerful alternative to {@link ufmtval_nextPosition}.
596 * If a field occurs just once, calling this method will find that occurrence and return it. If a
597 * field occurs multiple times, this method may be called repeatedly with the following pattern:
600 * UFieldPosition ufpos = {UNUM_GROUPING_SEPARATOR_FIELD, 0, 0};
601 * while (unumf_resultNextFieldPosition(uresult, ufpos, &ec)) {
602 * // do something with ufpos.
606 * This method is useful if you know which field to query. If you want all available field position
607 * information, use unumf_resultGetAllFieldPositions().
609 * NOTE: All fields of the UFieldPosition must be initialized before calling this method.
611 * @param uresult The object containing the formatted number.
613 * Input+output variable. On input, the "field" property determines which field to look up,
614 * and the "endIndex" property determines where to begin the search. On output, the
615 * "beginIndex" field is set to the beginning of the first occurrence of the field after the
616 * input "endIndex", and "endIndex" is set to the end of that occurrence of the field
617 * (exclusive index). If a field position is not found, the FieldPosition is not changed and
618 * the method returns FALSE.
619 * @param ec Set if an error occurs.
622 U_STABLE UBool U_EXPORT2
623 unumf_resultNextFieldPosition(const UFormattedNumber
* uresult
, UFieldPosition
* ufpos
, UErrorCode
* ec
);
627 * Populates the given iterator with all fields in the formatted output string. This allows you to
628 * determine the locations of the integer part, fraction part, and sign.
630 * This is an alternative to the more powerful {@link ufmtval_nextPosition} API.
632 * If you need information on only one field, use {@link ufmtval_nextPosition} or
633 * {@link unumf_resultNextFieldPosition}.
635 * @param uresult The object containing the formatted number.
637 * A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open}. Iteration
638 * information already present in the UFieldPositionIterator is deleted, and the iterator is reset
639 * to apply to the fields in the formatted string created by this function call. The field values
640 * and indexes returned by {@link #ufieldpositer_next} represent fields denoted by
641 * the UNumberFormatFields enum. Fields are not returned in a guaranteed order. Fields cannot
642 * overlap, but they may nest. For example, 1234 could format as "1,234" which might consist of a
643 * grouping separator field for ',' and an integer field encompassing the entire string.
644 * @param ec Set if an error occurs.
647 U_STABLE
void U_EXPORT2
648 unumf_resultGetAllFieldPositions(const UFormattedNumber
* uresult
, UFieldPositionIterator
* ufpositer
,
653 * Releases the UNumberFormatter created by unumf_openForSkeletonAndLocale().
655 * @param uformatter An object created by unumf_openForSkeletonAndLocale().
658 U_STABLE
void U_EXPORT2
659 unumf_close(UNumberFormatter
* uformatter
);
663 * Releases the UFormattedNumber created by unumf_openResult().
665 * @param uresult An object created by unumf_openResult().
668 U_STABLE
void U_EXPORT2
669 unumf_closeResult(UFormattedNumber
* uresult
);
672 #if U_SHOW_CPLUSPLUS_API
676 * \class LocalUNumberFormatterPointer
677 * "Smart pointer" class; closes a UNumberFormatter via unumf_close().
678 * For most methods see the LocalPointerBase base class.
682 * LocalUNumberFormatterPointer uformatter(unumf_openForSkeletonAndLocale(...));
683 * // no need to explicitly call unumf_close()
686 * @see LocalPointerBase
690 U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberFormatterPointer
, UNumberFormatter
, unumf_close
);
693 * \class LocalUFormattedNumberPointer
694 * "Smart pointer" class; closes a UFormattedNumber via unumf_closeResult().
695 * For most methods see the LocalPointerBase base class.
699 * LocalUFormattedNumberPointer uformatter(unumf_openResult(...));
700 * // no need to explicitly call unumf_closeResult()
703 * @see LocalPointerBase
707 U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedNumberPointer
, UFormattedNumber
, unumf_closeResult
);
710 #endif // U_SHOW_CPLUSPLUS_API
712 #endif //__UNUMBERFORMATTER_H__
713 #endif /* #if !UCONFIG_NO_FORMATTING */