codekingpro/portable-devtools
114k
1// © 2017 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
3
4#ifndef __NUMBERFORMATTER_H__
5#define __NUMBERFORMATTER_H__
6
7#include "unicode/utypes.h"
8
9#if U_SHOW_CPLUSPLUS_API
10
11#if !UCONFIG_NO_FORMATTING
12
13#include "unicode/appendable.h"
14#include "unicode/bytestream.h"
15#include "unicode/currunit.h"
16#include "unicode/dcfmtsym.h"
17#include "unicode/fieldpos.h"
18#include "unicode/formattedvalue.h"
19#include "unicode/fpositer.h"
20#include "unicode/measunit.h"
21#include "unicode/nounit.h"
22#include "unicode/parseerr.h"
23#include "unicode/plurrule.h"
24#include "unicode/ucurr.h"
25#include "unicode/unum.h"
26#include "unicode/unumberformatter.h"
27#include "unicode/uobject.h"
28
29/**
30 * \file
31 * \brief C++ API: Library for localized number formatting introduced in ICU 60.
32 *
33 * This library was introduced in ICU 60 to simplify the process of formatting localized number strings.
34 * Basic usage examples:
35 *
36 * <pre>
37 * // Most basic usage:
38 * NumberFormatter::withLocale(...).format(123).toString(); // 1,234 in en-US
39 *
40 * // Custom notation, unit, and rounding precision:
41 * NumberFormatter::with()
42 * .notation(Notation::compactShort())
43 * .unit(CurrencyUnit("EUR", status))
44 * .precision(Precision::maxDigits(2))
45 * .locale(...)
46 * .format(1234)
47 * .toString(); // €1.2K in en-US
48 *
49 * // Create a formatter in a singleton by value for use later:
50 * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...)
51 * .unit(NoUnit::percent())
52 * .precision(Precision::fixedFraction(3));
53 * formatter.format(5.9831).toString(); // 5.983% in en-US
54 *
55 * // Create a "template" in a singleton unique_ptr but without setting a locale until the call site:
56 * std::unique_ptr<UnlocalizedNumberFormatter> template = NumberFormatter::with()
57 * .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
58 * .unit(MeasureUnit::getMeter())
59 * .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
60 * .clone();
61 * template->locale(...).format(1234).toString(); // +1,234 meters in en-US
62 * </pre>
63 *
64 * <p>
65 * This API offers more features than DecimalFormat and is geared toward new users of ICU.
66 *
67 * <p>
68 * NumberFormatter instances (i.e., LocalizedNumberFormatter and UnlocalizedNumberFormatter)
69 * are immutable and thread safe. This means that invoking a configuration method has no
70 * effect on the receiving instance; you must store and use the new number formatter instance it returns instead.
71 *
72 * <pre>
73 * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific());
74 * formatter.precision(Precision.maxFraction(2)); // does nothing!
75 * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0"
76 * </pre>
77 *
78 * <p>
79 * This API is based on the <em>fluent</em> design pattern popularized by libraries such as Google's Guava. For
80 * extensive details on the design of this API, read <a href="https://goo.gl/szi5VB">the design doc</a>.
81 *
82 * @author Shane Carr
83 */
84
85U_NAMESPACE_BEGIN
86
87// Forward declarations:
88class IFixedDecimal;
89class FieldPositionIteratorHandler;
90class FormattedStringBuilder;
91
92namespace numparse {
93namespace impl {
94
95// Forward declarations:
96class NumberParserImpl;
97class MultiplierParseHandler;
98
99}
100}
101
102namespace number { // icu::number
103
104// Forward declarations:
105class UnlocalizedNumberFormatter;
106class LocalizedNumberFormatter;
107class FormattedNumber;
108class Notation;
109class ScientificNotation;
110class Precision;
111class FractionPrecision;
112class CurrencyPrecision;
113class IncrementPrecision;
114class IntegerWidth;
115
116namespace impl {
117
118// can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes
119/**
120 * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig.
121 *
122 * @internal
123 */
124typedef int16_t digits_t;
125
126// can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization
127/**
128 * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built
129 * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path.
130 *
131 * @internal
132 */
133static constexpr int32_t kInternalDefaultThreshold = 3;
134
135// Forward declarations:
136class Padder;
137struct MacroProps;
138struct MicroProps;
139class DecimalQuantity;
140class UFormattedNumberData;
141class NumberFormatterImpl;
142struct ParsedPatternInfo;
143class ScientificModifier;
144class MultiplierProducer;
145class RoundingImpl;
146class ScientificHandler;
147class Modifier;
148class AffixPatternProvider;
149class NumberPropertyMapper;
150struct DecimalFormatProperties;
151class MultiplierFormatHandler;
152class CurrencySymbols;
153class GeneratorHelpers;
154class DecNum;
155class NumberRangeFormatterImpl;
156struct RangeMacroProps;
157struct UFormattedNumberImpl;
158class MutablePatternModifier;
159class ImmutablePatternModifier;
160
161/**
162 * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp.
163 * Declared here so it can be friended.
164 *
165 * @internal
166 */
167void touchRangeLocales(impl::RangeMacroProps& macros);
168
169} // namespace impl
170
171/**
172 * Extra name reserved in case it is needed in the future.
173 *
174 * @stable ICU 63
175 */
176typedef Notation CompactNotation;
177
178/**
179 * Extra name reserved in case it is needed in the future.
180 *
181 * @stable ICU 63
182 */
183typedef Notation SimpleNotation;
184
185/**
186 * A class that defines the notation style to be used when formatting numbers in NumberFormatter.
187 *
188 * @stable ICU 60
189 */
190class U_I18N_API Notation : public UMemory {
191 public:
192 /**
193 * Print the number using scientific notation (also known as scientific form, standard index form, or standard form
194 * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the
195 * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more
196 * digits after the decimal separator, and the corresponding power of 10 displayed after the "E".
197 *
198 * <p>
199 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
200 *
201 * <pre>
202 * 8.765E4
203 * 8.765E3
204 * 8.765E2
205 * 8.765E1
206 * 8.765E0
207 * 8.765E-1
208 * 8.765E-2
209 * 8.765E-3
210 * 0E0
211 * </pre>
212 *
213 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
214 * @stable ICU 60
215 */
216 static ScientificNotation scientific();
217
218 /**
219 * Print the number using engineering notation, a variant of scientific notation in which the exponent must be
220 * divisible by 3.
221 *
222 * <p>
223 * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
224 *
225 * <pre>
226 * 87.65E3
227 * 8.765E3
228 * 876.5E0
229 * 87.65E0
230 * 8.765E0
231 * 876.5E-3
232 * 87.65E-3
233 * 8.765E-3
234 * 0E0
235 * </pre>
236 *
237 * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
238 * @stable ICU 60
239 */
240 static ScientificNotation engineering();
241
242 /**
243 * Print the number using short-form compact notation.
244 *
245 * <p>
246 * <em>Compact notation</em>, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with
247 * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to
248 * engineering notation in how it scales numbers.
249 *
250 * <p>
251 * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing
252 * screen real estate.
253 *
254 * <p>
255 * In short form, the powers of ten are abbreviated. In <em>en-US</em>, the abbreviations are "K" for thousands, "M"
256 * for millions, "B" for billions, and "T" for trillions. Example outputs in <em>en-US</em> when printing 8.765E7
257 * through 8.765E0:
258 *
259 * <pre>
260 * 88M
261 * 8.8M
262 * 876K
263 * 88K
264 * 8.8K
265 * 876
266 * 88
267 * 8.8
268 * </pre>
269 *
270 * <p>
271 * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest
272 * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal
273 * separator if there is only one digit before the decimal separator. The default compact notation rounding precision
274 * is equivalent to:
275 *
276 * <pre>
277 * Precision::integer().withMinDigits(2)
278 * </pre>
279 *
280 * @return A CompactNotation for passing to the NumberFormatter notation() setter.
281 * @stable ICU 60
282 */
283 static CompactNotation compactShort();
284
285 /**
286 * Print the number using long-form compact notation. For more information on compact notation, see
287 * {@link #compactShort}.
288 *
289 * <p>
290 * In long form, the powers of ten are spelled out fully. Example outputs in <em>en-US</em> when printing 8.765E7
291 * through 8.765E0:
292 *
293 * <pre>
294 * 88 million
295 * 8.8 million
296 * 876 thousand
297 * 88 thousand
298 * 8.8 thousand
299 * 876
300 * 88
301 * 8.8
302 * </pre>
303 *
304 * @return A CompactNotation for passing to the NumberFormatter notation() setter.
305 * @stable ICU 60
306 */
307 static CompactNotation compactLong();
308
309 /**
310 * Print the number using simple notation without any scaling by powers of ten. This is the default behavior.
311 *
312 * <p>
313 * Since this is the default behavior, this method needs to be called only when it is necessary to override a
314 * previous setting.
315 *
316 * <p>
317 * Example outputs in <em>en-US</em> when printing 8.765E7 through 8.765E0:
318 *
319 * <pre>
320 * 87,650,000
321 * 8,765,000
322 * 876,500
323 * 87,650
324 * 8,765
325 * 876.5
326 * 87.65
327 * 8.765
328 * </pre>
329 *
330 * @return A SimpleNotation for passing to the NumberFormatter notation() setter.
331 * @stable ICU 60
332 */
333 static SimpleNotation simple();
334
335 private:
336 enum NotationType {
337 NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR
338 } fType;
339
340 union NotationUnion {
341 // For NTN_SCIENTIFIC
342 /** @internal */
343 struct ScientificSettings {
344 /** @internal */
345 int8_t fEngineeringInterval;
346 /** @internal */
347 bool fRequireMinInt;
348 /** @internal */
349 impl::digits_t fMinExponentDigits;
350 /** @internal */
351 UNumberSignDisplay fExponentSignDisplay;
352 } scientific;
353
354 // For NTN_COMPACT
355 UNumberCompactStyle compactStyle;
356
357 // For NTN_ERROR
358 UErrorCode errorCode;
359 } fUnion;
360
361 typedef NotationUnion::ScientificSettings ScientificSettings;
362
363 Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {}
364
365 Notation(UErrorCode errorCode) : fType(NTN_ERROR) {
366 fUnion.errorCode = errorCode;
367 }
368
369 Notation() : fType(NTN_SIMPLE), fUnion() {}
370
371 UBool copyErrorTo(UErrorCode &status) const {
372 if (fType == NTN_ERROR) {
373 status = fUnion.errorCode;
374 return TRUE;
375 }
376 return FALSE;
377 }
378
379 // To allow MacroProps to initialize empty instances:
380 friend struct impl::MacroProps;
381 friend class ScientificNotation;
382
383 // To allow implementation to access internal types:
384 friend class impl::NumberFormatterImpl;
385 friend class impl::ScientificModifier;
386 friend class impl::ScientificHandler;
387
388 // To allow access to the skeleton generation code:
389 friend class impl::GeneratorHelpers;
390};
391
392/**
393 * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter.
394 *
395 * <p>
396 * To create a ScientificNotation, use one of the factory methods in {@link Notation}.
397 *
398 * @stable ICU 60
399 */
400class U_I18N_API ScientificNotation : public Notation {
401 public:
402 /**
403 * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if
404 * necessary. Useful for fixed-width display.
405 *
406 * <p>
407 * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in <em>en-US</em> instead of
408 * the default "1.23E2".
409 *
410 * @param minExponentDigits
411 * The minimum number of digits to show in the exponent.
412 * @return A ScientificNotation, for chaining.
413 * @stable ICU 60
414 */
415 ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const;
416
417 /**
418 * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO,
419 * showing the minus sign but not the plus sign.
420 *
421 * <p>
422 * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in <em>en-US</em>
423 * instead of the default "1.23E2".
424 *
425 * @param exponentSignDisplay
426 * The strategy for displaying the sign in the exponent.
427 * @return A ScientificNotation, for chaining.
428 * @stable ICU 60
429 */
430 ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const;
431
432 private:
433 // Inherit constructor
434 using Notation::Notation;
435
436 // Raw constructor for NumberPropertyMapper
437 ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits,
438 UNumberSignDisplay fExponentSignDisplay);
439
440 friend class Notation;
441
442 // So that NumberPropertyMapper can create instances
443 friend class impl::NumberPropertyMapper;
444};
445
446/**
447 * Extra name reserved in case it is needed in the future.
448 *
449 * @stable ICU 63
450 */
451typedef Precision SignificantDigitsPrecision;
452
453/**
454 * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter.
455 *
456 * <p>
457 * To create a Precision, use one of the factory methods.
458 *
459 * @stable ICU 60
460 */
461class U_I18N_API Precision : public UMemory {
462
463 public:
464 /**
465 * Show all available digits to full precision.
466 *
467 * <p>
468 * <strong>NOTE:</strong> When formatting a <em>double</em>, this method, along with {@link #minFraction} and
469 * {@link #minSignificantDigits}, will trigger complex algorithm similar to <em>Dragon4</em> to determine the
470 * low-order digits and the number of digits to display based on the value of the double.
471 * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction}
472 * or {@link #maxSignificantDigits} instead to maximize performance.
473 * For more information, read the following blog post.
474 *
475 * <p>
476 * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/
477 *
478 * @return A Precision for chaining or passing to the NumberFormatter precision() setter.
479 * @stable ICU 60
480 */
481 static Precision unlimited();
482
483 /**
484 * Show numbers rounded if necessary to the nearest integer.
485 *
486 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
487 * @stable ICU 60
488 */
489 static FractionPrecision integer();
490
491 /**
492 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
493 * Additionally, pad with zeros to ensure that this number of places are always shown.
494 *
495 * <p>
496 * Example output with minMaxFractionPlaces = 3:
497 *
498 * <p>
499 * 87,650.000<br>
500 * 8,765.000<br>
501 * 876.500<br>
502 * 87.650<br>
503 * 8.765<br>
504 * 0.876<br>
505 * 0.088<br>
506 * 0.009<br>
507 * 0.000 (zero)
508 *
509 * <p>
510 * This method is equivalent to {@link #minMaxFraction} with both arguments equal.
511 *
512 * @param minMaxFractionPlaces
513 * The minimum and maximum number of numerals to display after the decimal separator (rounding if too
514 * long or padding with zeros if too short).
515 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
516 * @stable ICU 60
517 */
518 static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces);
519
520 /**
521 * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if
522 * necessary. Do not perform rounding (display numbers to their full precision).
523 *
524 * <p>
525 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
526 *
527 * @param minFractionPlaces
528 * The minimum number of numerals to display after the decimal separator (padding with zeros if
529 * necessary).
530 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
531 * @stable ICU 60
532 */
533 static FractionPrecision minFraction(int32_t minFractionPlaces);
534
535 /**
536 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
537 * Unlike the other fraction rounding strategies, this strategy does <em>not</em> pad zeros to the end of the
538 * number.
539 *
540 * @param maxFractionPlaces
541 * The maximum number of numerals to display after the decimal mark (rounding if necessary).
542 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
543 * @stable ICU 60
544 */
545 static FractionPrecision maxFraction(int32_t maxFractionPlaces);
546
547 /**
548 * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator);
549 * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if
550 * necessary.
551 *
552 * @param minFractionPlaces
553 * The minimum number of numerals to display after the decimal separator (padding with zeros if
554 * necessary).
555 * @param maxFractionPlaces
556 * The maximum number of numerals to display after the decimal separator (rounding if necessary).
557 * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
558 * @stable ICU 60
559 */
560 static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces);
561
562 /**
563 * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally,
564 * pad with zeros to ensure that this number of significant digits/figures are always shown.
565 *
566 * <p>
567 * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal.
568 *
569 * @param minMaxSignificantDigits
570 * The minimum and maximum number of significant digits to display (rounding if too long or padding with
571 * zeros if too short).
572 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
573 * @stable ICU 62
574 */
575 static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits);
576
577 /**
578 * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not
579 * perform rounding (display numbers to their full precision).
580 *
581 * <p>
582 * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
583 *
584 * @param minSignificantDigits
585 * The minimum number of significant digits to display (padding with zeros if too short).
586 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
587 * @stable ICU 62
588 */
589 static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits);
590
591 /**
592 * Show numbers rounded if necessary to a certain number of significant digits/figures.
593 *
594 * @param maxSignificantDigits
595 * The maximum number of significant digits to display (rounding if too long).
596 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
597 * @stable ICU 62
598 */
599 static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits);
600
601 /**
602 * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at
603 * least a certain number of significant digits, padding with zeros if necessary.
604 *
605 * @param minSignificantDigits
606 * The minimum number of significant digits to display (padding with zeros if necessary).
607 * @param maxSignificantDigits
608 * The maximum number of significant digits to display (rounding if necessary).
609 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
610 * @stable ICU 62
611 */
612 static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits,
613 int32_t maxSignificantDigits);
614
615 /**
616 * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the
617 * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5.
618 *
619 * <p>
620 * In order to ensure that numbers are padded to the appropriate number of fraction places, call
621 * withMinFraction() on the return value of this method.
622 * For example, to round to the nearest 0.5 and always display 2 numerals after the
623 * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run:
624 *
625 * <pre>
626 * Precision::increment(0.5).withMinFraction(2)
627 * </pre>
628 *
629 * @param roundingIncrement
630 * The increment to which to round numbers.
631 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
632 * @stable ICU 60
633 */
634 static IncrementPrecision increment(double roundingIncrement);
635
636 /**
637 * Show numbers rounded and padded according to the rules for the currency unit. The most common
638 * rounding precision settings for currencies include <code>Precision::fixedFraction(2)</code>,
639 * <code>Precision::integer()</code>, and <code>Precision::increment(0.05)</code> for cash transactions
640 * ("nickel rounding").
641 *
642 * <p>
643 * The exact rounding details will be resolved at runtime based on the currency unit specified in the
644 * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another
645 * currency, the withCurrency() method can be called on the return value of this method.
646 *
647 * @param currencyUsage
648 * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may
649 * be limited by the available denominations of cash or coins).
650 * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter.
651 * @stable ICU 60
652 */
653 static CurrencyPrecision currency(UCurrencyUsage currencyUsage);
654
655 private:
656 enum PrecisionType {
657 RND_BOGUS,
658 RND_NONE,
659 RND_FRACTION,
660 RND_SIGNIFICANT,
661 RND_FRACTION_SIGNIFICANT,
662
663 // Used for strange increments like 3.14.
664 RND_INCREMENT,
665
666 // Used for increments with 1 as the only digit. This is different than fraction
667 // rounding because it supports having additional trailing zeros. For example, this
668 // class is used to round with the increment 0.010.
669 RND_INCREMENT_ONE,
670
671 // Used for increments with 5 as the only digit (nickel rounding).
672 RND_INCREMENT_FIVE,
673
674 RND_CURRENCY,
675 RND_ERROR
676 } fType;
677
678 union PrecisionUnion {
679 /** @internal */
680 struct FractionSignificantSettings {
681 // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT
682 /** @internal */
683 impl::digits_t fMinFrac;
684 /** @internal */
685 impl::digits_t fMaxFrac;
686 /** @internal */
687 impl::digits_t fMinSig;
688 /** @internal */
689 impl::digits_t fMaxSig;
690 } fracSig;
691 /** @internal */
692 struct IncrementSettings {
693 // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE
694 /** @internal */
695 double fIncrement;
696 /** @internal */
697 impl::digits_t fMinFrac;
698 /** @internal */
699 impl::digits_t fMaxFrac;
700 } increment;
701 UCurrencyUsage currencyUsage; // For RND_CURRENCY
702 UErrorCode errorCode; // For RND_ERROR
703 } fUnion;
704
705 typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings;
706 typedef PrecisionUnion::IncrementSettings IncrementSettings;
707
708 /** The Precision encapsulates the RoundingMode when used within the implementation. */
709 UNumberFormatRoundingMode fRoundingMode;
710
711 Precision(const PrecisionType& type, const PrecisionUnion& union_,
712 UNumberFormatRoundingMode roundingMode)
713 : fType(type), fUnion(union_), fRoundingMode(roundingMode) {}
714
715 Precision(UErrorCode errorCode) : fType(RND_ERROR) {
716 fUnion.errorCode = errorCode;
717 }
718
719 Precision() : fType(RND_BOGUS) {}
720
721 bool isBogus() const {
722 return fType == RND_BOGUS;
723 }
724
725 UBool copyErrorTo(UErrorCode &status) const {
726 if (fType == RND_ERROR) {
727 status = fUnion.errorCode;
728 return TRUE;
729 }
730 return FALSE;
731 }
732
733 // On the parent type so that this method can be called internally on Precision instances.
734 Precision withCurrency(const CurrencyUnit ¤cy, UErrorCode &status) const;
735
736 static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac);
737
738 static Precision constructSignificant(int32_t minSig, int32_t maxSig);
739
740 static Precision
741 constructFractionSignificant(const FractionPrecision &base, int32_t minSig, int32_t maxSig);
742
743 static IncrementPrecision constructIncrement(double increment, int32_t minFrac);
744
745 static CurrencyPrecision constructCurrency(UCurrencyUsage usage);
746
747 static Precision constructPassThrough();
748
749 // To allow MacroProps/MicroProps to initialize bogus instances:
750 friend struct impl::MacroProps;
751 friend struct impl::MicroProps;
752
753 // To allow NumberFormatterImpl to access isBogus() and other internal methods:
754 friend class impl::NumberFormatterImpl;
755
756 // To allow NumberPropertyMapper to create instances from DecimalFormatProperties:
757 friend class impl::NumberPropertyMapper;
758
759 // To allow access to the main implementation class:
760 friend class impl::RoundingImpl;
761
762 // To allow child classes to call private methods:
763 friend class FractionPrecision;
764 friend class CurrencyPrecision;
765 friend class IncrementPrecision;
766
767 // To allow access to the skeleton generation code:
768 friend class impl::GeneratorHelpers;
769};
770
771/**
772 * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be
773 * used when formatting numbers in NumberFormatter.
774 *
775 * <p>
776 * To create a FractionPrecision, use one of the factory methods on Precision.
777 *
778 * @stable ICU 60
779 */
780class U_I18N_API FractionPrecision : public Precision {
781 public:
782 /**
783 * Ensure that no less than this number of significant digits are retained when rounding according to fraction
784 * rules.
785 *
786 * <p>
787 * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum figures set to 2, 3.141
788 * becomes "3.1" instead.
789 *
790 * <p>
791 * This setting does not affect the number of trailing zeros. For example, 3.01 would print as "3", not "3.0".
792 *
793 * @param minSignificantDigits
794 * The number of significant figures to guarantee.
795 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
796 * @stable ICU 60
797 */
798 Precision withMinDigits(int32_t minSignificantDigits) const;
799
800 /**
801 * Ensure that no more than this number of significant digits are retained when rounding according to fraction
802 * rules.
803 *
804 * <p>
805 * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum figures set to 2, 123.4
806 * becomes "120" instead.
807 *
808 * <p>
809 * This setting does not affect the number of trailing zeros. For example, with fixed fraction of 2, 123.4 would
810 * become "120.00".
811 *
812 * @param maxSignificantDigits
813 * Round the number to no more than this number of significant figures.
814 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
815 * @stable ICU 60
816 */
817 Precision withMaxDigits(int32_t maxSignificantDigits) const;
818
819 private:
820 // Inherit constructor
821 using Precision::Precision;
822
823 // To allow parent class to call this class's constructor:
824 friend class Precision;
825};
826
827/**
828 * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in
829 * NumberFormatter.
830 *
831 * <p>
832 * To create a CurrencyPrecision, use one of the factory methods on Precision.
833 *
834 * @stable ICU 60
835 */
836class U_I18N_API CurrencyPrecision : public Precision {
837 public:
838 /**
839 * Associates a currency with this rounding precision.
840 *
841 * <p>
842 * <strong>Calling this method is <em>not required</em></strong>, because the currency specified in unit()
843 * is automatically applied to currency rounding precisions. However,
844 * this method enables you to override that automatic association.
845 *
846 * <p>
847 * This method also enables numbers to be formatted using currency rounding rules without explicitly using a
848 * currency format.
849 *
850 * @param currency
851 * The currency to associate with this rounding precision.
852 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
853 * @stable ICU 60
854 */
855 Precision withCurrency(const CurrencyUnit ¤cy) const;
856
857 private:
858 // Inherit constructor
859 using Precision::Precision;
860
861 // To allow parent class to call this class's constructor:
862 friend class Precision;
863};
864
865/**
866 * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in
867 * NumberFormatter.
868 *
869 * <p>
870 * To create an IncrementPrecision, use one of the factory methods on Precision.
871 *
872 * @stable ICU 60
873 */
874class U_I18N_API IncrementPrecision : public Precision {
875 public:
876 /**
877 * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if
878 * necessary. By default, no trailing zeros are added.
879 *
880 * <p>
881 * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00",
882 * "0.50", "1.00", and "1.50".
883 *
884 * <p>
885 * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment.
886 *
887 * @param minFrac The minimum number of digits after the decimal separator.
888 * @return A precision for chaining or passing to the NumberFormatter precision() setter.
889 * @stable ICU 60
890 */
891 Precision withMinFraction(int32_t minFrac) const;
892
893 private:
894 // Inherit constructor
895 using Precision::Precision;
896
897 // To allow parent class to call this class's constructor:
898 friend class Precision;
899};
900
901/**
902 * A class that defines the strategy for padding and truncating integers before the decimal separator.
903 *
904 * <p>
905 * To create an IntegerWidth, use one of the factory methods.
906 *
907 * @stable ICU 60
908 * @see NumberFormatter
909 */
910class U_I18N_API IntegerWidth : public UMemory {
911 public:
912 /**
913 * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator.
914 *
915 * <p>
916 * For example, with minInt=3, the number 55 will get printed as "055".
917 *
918 * @param minInt
919 * The minimum number of places before the decimal separator.
920 * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter.
921 * @stable ICU 60
922 */
923 static IntegerWidth zeroFillTo(int32_t minInt);
924
925 /**
926 * Truncate numbers exceeding a certain number of numerals before the decimal separator.
927 *
928 * For example, with maxInt=3, the number 1234 will get printed as "234".
929 *
930 * @param maxInt
931 * The maximum number of places before the decimal separator. maxInt == -1 means no
932 * truncation.
933 * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter.
934 * @stable ICU 60
935 */
936 IntegerWidth truncateAt(int32_t maxInt);
937
938 private:
939 union {
940 struct {
941 impl::digits_t fMinInt;
942 impl::digits_t fMaxInt;
943 bool fFormatFailIfMoreThanMaxDigits;
944 } minMaxInt;
945 UErrorCode errorCode;
946 } fUnion;
947 bool fHasError = false;
948
949 IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits);
950
951 IntegerWidth(UErrorCode errorCode) { // NOLINT
952 fUnion.errorCode = errorCode;
953 fHasError = true;
954 }
955
956 IntegerWidth() { // NOLINT
957 fUnion.minMaxInt.fMinInt = -1;
958 }
959
960 /** Returns the default instance. */
961 static IntegerWidth standard() {
962 return IntegerWidth::zeroFillTo(1);
963 }
964
965 bool isBogus() const {
966 return !fHasError && fUnion.minMaxInt.fMinInt == -1;
967 }
968
969 UBool copyErrorTo(UErrorCode &status) const {
970 if (fHasError) {
971 status = fUnion.errorCode;
972 return TRUE;
973 }
974 return FALSE;
975 }
976
977 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const;
978
979 bool operator==(const IntegerWidth& other) const;
980
981 // To allow MacroProps/MicroProps to initialize empty instances:
982 friend struct impl::MacroProps;
983 friend struct impl::MicroProps;
984
985 // To allow NumberFormatterImpl to access isBogus():
986 friend class impl::NumberFormatterImpl;
987
988 // To allow the use of this class when formatting:
989 friend class impl::MutablePatternModifier;
990 friend class impl::ImmutablePatternModifier;
991
992 // So that NumberPropertyMapper can create instances
993 friend class impl::NumberPropertyMapper;
994
995 // To allow access to the skeleton generation code:
996 friend class impl::GeneratorHelpers;
997};
998
999/**
1000 * A class that defines a quantity by which a number should be multiplied when formatting.
1001 *
1002 * <p>
1003 * To create a Scale, use one of the factory methods.
1004 *
1005 * @stable ICU 62
1006 */
1007class U_I18N_API Scale : public UMemory {
1008 public:
1009 /**
1010 * Do not change the value of numbers when formatting or parsing.
1011 *
1012 * @return A Scale to prevent any multiplication.
1013 * @stable ICU 62
1014 */
1015 static Scale none();
1016
1017 /**
1018 * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit:
1019 *
1020 * <pre>
1021 * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2))
1022 * </pre>
1023 *
1024 * @return A Scale for passing to the setter in NumberFormatter.
1025 * @stable ICU 62
1026 */
1027 static Scale powerOfTen(int32_t power);
1028
1029 /**
1030 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
1031 *
1032 * This method takes a string in a decimal number format with syntax
1033 * as defined in the Decimal Arithmetic Specification, available at
1034 * http://speleotrove.com/decimal
1035 *
1036 * Also see the version of this method that takes a double.
1037 *
1038 * @return A Scale for passing to the setter in NumberFormatter.
1039 * @stable ICU 62
1040 */
1041 static Scale byDecimal(StringPiece multiplicand);
1042
1043 /**
1044 * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
1045 *
1046 * This method takes a double; also see the version of this method that takes an exact decimal.
1047 *
1048 * @return A Scale for passing to the setter in NumberFormatter.
1049 * @stable ICU 62
1050 */
1051 static Scale byDouble(double multiplicand);
1052
1053 /**
1054 * Multiply a number by both a power of ten and by an arbitrary double value.
1055 *
1056 * @return A Scale for passing to the setter in NumberFormatter.
1057 * @stable ICU 62
1058 */
1059 static Scale byDoubleAndPowerOfTen(double multiplicand, int32_t power);
1060
1061 // We need a custom destructor for the DecNum, which means we need to declare
1062 // the copy/move constructor/assignment quartet.
1063
1064 /** @stable ICU 62 */
1065 Scale(const Scale& other);
1066
1067 /** @stable ICU 62 */
1068 Scale& operator=(const Scale& other);
1069
1070 /** @stable ICU 62 */
1071 Scale(Scale&& src) U_NOEXCEPT;
1072
1073 /** @stable ICU 62 */
1074 Scale& operator=(Scale&& src) U_NOEXCEPT;
1075
1076 /** @stable ICU 62 */
1077 ~Scale();
1078
1079#ifndef U_HIDE_INTERNAL_API
1080 /** @internal */
1081 Scale(int32_t magnitude, impl::DecNum* arbitraryToAdopt);
1082#endif /* U_HIDE_INTERNAL_API */
1083
1084 private:
1085 int32_t fMagnitude;
1086 impl::DecNum* fArbitrary;
1087 UErrorCode fError;
1088
1089 Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {}
1090
1091 Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {}
1092
1093 bool isValid() const {
1094 return fMagnitude != 0 || fArbitrary != nullptr;
1095 }
1096
1097 UBool copyErrorTo(UErrorCode &status) const {
1098 if (fError != U_ZERO_ERROR) {
1099 status = fError;
1100 return TRUE;
1101 }
1102 return FALSE;
1103 }
1104
1105 void applyTo(impl::DecimalQuantity& quantity) const;
1106
1107 void applyReciprocalTo(impl::DecimalQuantity& quantity) const;
1108
1109 // To allow MacroProps/MicroProps to initialize empty instances:
1110 friend struct impl::MacroProps;
1111 friend struct impl::MicroProps;
1112
1113 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1114 friend class impl::NumberFormatterImpl;
1115
1116 // To allow the helper class MultiplierFormatHandler access to private fields:
1117 friend class impl::MultiplierFormatHandler;
1118
1119 // To allow access to the skeleton generation code:
1120 friend class impl::GeneratorHelpers;
1121
1122 // To allow access to parsing code:
1123 friend class ::icu::numparse::impl::NumberParserImpl;
1124 friend class ::icu::numparse::impl::MultiplierParseHandler;
1125};
1126
1127namespace impl {
1128
1129// Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1130/** @internal */
1131class U_I18N_API SymbolsWrapper : public UMemory {
1132 public:
1133 /** @internal */
1134 SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {}
1135
1136 /** @internal */
1137 SymbolsWrapper(const SymbolsWrapper &other);
1138
1139 /** @internal */
1140 SymbolsWrapper &operator=(const SymbolsWrapper &other);
1141
1142 /** @internal */
1143 SymbolsWrapper(SymbolsWrapper&& src) U_NOEXCEPT;
1144
1145 /** @internal */
1146 SymbolsWrapper &operator=(SymbolsWrapper&& src) U_NOEXCEPT;
1147
1148 /** @internal */
1149 ~SymbolsWrapper();
1150
1151#ifndef U_HIDE_INTERNAL_API
1152
1153 /**
1154 * The provided object is copied, but we do not adopt it.
1155 * @internal
1156 */
1157 void setTo(const DecimalFormatSymbols &dfs);
1158
1159 /**
1160 * Adopt the provided object.
1161 * @internal
1162 */
1163 void setTo(const NumberingSystem *ns);
1164
1165 /**
1166 * Whether the object is currently holding a DecimalFormatSymbols.
1167 * @internal
1168 */
1169 bool isDecimalFormatSymbols() const;
1170
1171 /**
1172 * Whether the object is currently holding a NumberingSystem.
1173 * @internal
1174 */
1175 bool isNumberingSystem() const;
1176
1177 /**
1178 * Get the DecimalFormatSymbols pointer. No ownership change.
1179 * @internal
1180 */
1181 const DecimalFormatSymbols *getDecimalFormatSymbols() const;
1182
1183 /**
1184 * Get the NumberingSystem pointer. No ownership change.
1185 * @internal
1186 */
1187 const NumberingSystem *getNumberingSystem() const;
1188
1189#endif // U_HIDE_INTERNAL_API
1190
1191 /** @internal */
1192 UBool copyErrorTo(UErrorCode &status) const {
1193 if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) {
1194 status = U_MEMORY_ALLOCATION_ERROR;
1195 return TRUE;
1196 } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) {
1197 status = U_MEMORY_ALLOCATION_ERROR;
1198 return TRUE;
1199 }
1200 return FALSE;
