ICU 74.2 74.2
numberformatter.h
Go to the documentation of this file.
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"
18#include "unicode/fieldpos.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"
27#include "unicode/uobject.h"
30
89U_NAMESPACE_BEGIN
90
91// Forward declarations:
92class IFixedDecimal;
93class FieldPositionIteratorHandler;
94class FormattedStringBuilder;
95
96namespace numparse {
97namespace impl {
98
99// Forward declarations:
100class NumberParserImpl;
101class MultiplierParseHandler;
102
103}
104}
105
106namespace units {
107
108// Forward declarations:
109class UnitsRouter;
110
111} // namespace units
112
113namespace number { // icu::number
114
115// Forward declarations:
116class UnlocalizedNumberFormatter;
117class LocalizedNumberFormatter;
118class SimpleNumberFormatter;
119class FormattedNumber;
120class Notation;
121class ScientificNotation;
122class Precision;
123class FractionPrecision;
124class CurrencyPrecision;
125class IncrementPrecision;
126class IntegerWidth;
127
128namespace impl {
129
130// can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes
137
138// can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization
145static constexpr int32_t kInternalDefaultThreshold = 3;
146
147// Forward declarations:
148class Padder;
149struct MacroProps;
150struct MicroProps;
151class DecimalQuantity;
153class NumberFormatterImpl;
154struct ParsedPatternInfo;
155class ScientificModifier;
157class RoundingImpl;
158class ScientificHandler;
159class Modifier;
161class NumberPropertyMapper;
163class MultiplierFormatHandler;
164class CurrencySymbols;
165class GeneratorHelpers;
166class DecNum;
167class NumberRangeFormatterImpl;
168struct RangeMacroProps;
169struct UFormattedNumberImpl;
170class MutablePatternModifier;
171class ImmutablePatternModifier;
173struct SimpleMicroProps;
175
183
184} // namespace impl
185
192
199
206 public:
232
256
299
323
349
350 private:
351 enum NotationType {
352 NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR
353 } fType;
354
355 union NotationUnion {
356 // For NTN_SCIENTIFIC
368
369 // For NTN_COMPACT
370 UNumberCompactStyle compactStyle;
371
372 // For NTN_ERROR
373 UErrorCode errorCode;
374 } fUnion;
375
377
378 Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {}
379
380 Notation(UErrorCode errorCode) : fType(NTN_ERROR) {
381 fUnion.errorCode = errorCode;
382 }
383
384 Notation() : fType(NTN_SIMPLE), fUnion() {}
385
386 UBool copyErrorTo(UErrorCode &status) const {
387 if (fType == NTN_ERROR) {
388 status = fUnion.errorCode;
389 return true;
390 }
391 return false;
392 }
393
394 // To allow MacroProps to initialize empty instances:
395 friend struct impl::MacroProps;
396 friend class ScientificNotation;
397
398 // To allow implementation to access internal types:
399 friend class impl::NumberFormatterImpl;
400 friend class impl::ScientificModifier;
401 friend class impl::ScientificHandler;
402
403 // To allow access to the skeleton generation code:
404 friend class impl::GeneratorHelpers;
405};
406
416 public:
431
446
447 private:
448 // Inherit constructor
449 using Notation::Notation;
450
451 // Raw constructor for NumberPropertyMapper
452 ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits,
453 UNumberSignDisplay fExponentSignDisplay);
454
455 friend class Notation;
456
457 // So that NumberPropertyMapper can create instances
458 friend class impl::NumberPropertyMapper;
459};
460
467
477
478 public:
497
505
534
549
561
576
591
605
615
628 int32_t maxSignificantDigits);
629
650
675
694
703
704 private:
705 enum PrecisionType {
706 RND_BOGUS,
707 RND_NONE,
708 RND_FRACTION,
709 RND_SIGNIFICANT,
710 RND_FRACTION_SIGNIFICANT,
711
712 // Used for strange increments like 3.14.
713 RND_INCREMENT,
714
715 // Used for increments with 1 as the only digit. This is different than fraction
716 // rounding because it supports having additional trailing zeros. For example, this
717 // class is used to round with the increment 0.010.
718 RND_INCREMENT_ONE,
719
720 // Used for increments with 5 as the only digit (nickel rounding).
721 RND_INCREMENT_FIVE,
722
723 RND_CURRENCY,
724 RND_ERROR
725 } fType;
726
727 union PrecisionUnion {
749 // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE
750 // Note: This is a union, so we shouldn't own memory, since
751 // the default destructor would leak it.
758 } increment;
759 UCurrencyUsage currencyUsage; // For RND_CURRENCY
760 UErrorCode errorCode; // For RND_ERROR
761 } fUnion;
762
764
767
768 Precision(const PrecisionType& type, const PrecisionUnion& union_)
769 : fType(type), fUnion(union_) {}
770
771 Precision(UErrorCode errorCode) : fType(RND_ERROR) {
772 fUnion.errorCode = errorCode;
773 }
774
775 Precision() : fType(RND_BOGUS) {}
776
777 bool isBogus() const {
778 return fType == RND_BOGUS;
779 }
780
781 UBool copyErrorTo(UErrorCode &status) const {
782 if (fType == RND_ERROR) {
783 status = fUnion.errorCode;
784 return true;
785 }
786 return false;
787 }
788
789 // On the parent type so that this method can be called internally on Precision instances.
790 Precision withCurrency(const CurrencyUnit &currency, UErrorCode &status) const;
791
792 static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac);
793
794 static Precision constructSignificant(int32_t minSig, int32_t maxSig);
795
796 static Precision constructFractionSignificant(
797 const FractionPrecision &base,
798 int32_t minSig,
799 int32_t maxSig,
801 bool retain);
802
803 static IncrementPrecision constructIncrement(uint64_t increment, impl::digits_t magnitude);
804
805 static CurrencyPrecision constructCurrency(UCurrencyUsage usage);
806
807 // To allow MacroProps/MicroProps to initialize bogus instances:
808 friend struct impl::MacroProps;
809 friend struct impl::MicroProps;
810
811 // To allow NumberFormatterImpl to access isBogus() and other internal methods:
812 friend class impl::NumberFormatterImpl;
813
814 // To allow NumberPropertyMapper to create instances from DecimalFormatProperties:
815 friend class impl::NumberPropertyMapper;
816
817 // To allow access to the main implementation class:
818 friend class impl::RoundingImpl;
819
820 // To allow child classes to call private methods:
821 friend class FractionPrecision;
822 friend class CurrencyPrecision;
823 friend class IncrementPrecision;
824
825 // To allow access to the skeleton generation code:
826 friend class impl::GeneratorHelpers;
827
828 // To allow access to isBogus and the default (bogus) constructor:
829 friend class units::UnitsRouter;
830};
831
842 public:
858 int32_t minSignificantDigits,
859 int32_t maxSignificantDigits,
861
879 Precision withMinDigits(int32_t minSignificantDigits) const;
880
898 Precision withMaxDigits(int32_t maxSignificantDigits) const;
899
900 private:
901 // Inherit constructor
902 using Precision::Precision;
903
904 // To allow parent class to call this class's constructor:
905 friend class Precision;
906};
907
918 public:
936 Precision withCurrency(const CurrencyUnit &currency) const;
937
938 private:
939 // Inherit constructor
940 using Precision::Precision;
941
942 // To allow parent class to call this class's constructor:
943 friend class Precision;
944};
945
956 public:
973
974 private:
975 // Inherit constructor
976 using Precision::Precision;
977
978 // To allow parent class to call this class's constructor:
979 friend class Precision;
980};
981
992 public:
1005
1018
1019 private:
1020 union {
1021 struct {
1022 impl::digits_t fMinInt;
1023 impl::digits_t fMaxInt;
1024 bool fFormatFailIfMoreThanMaxDigits;
1025 } minMaxInt;
1026 UErrorCode errorCode;
1027 } fUnion;
1028 bool fHasError = false;
1029
1030 IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits);
1031
1032 IntegerWidth(UErrorCode errorCode) { // NOLINT
1033 fUnion.errorCode = errorCode;
1034 fHasError = true;
1035 }
1036
1037 IntegerWidth() { // NOLINT
1038 fUnion.minMaxInt.fMinInt = -1;
1039 }
1040
1042 static IntegerWidth standard() {
1043 return IntegerWidth::zeroFillTo(1);
1044 }
1045
1046 bool isBogus() const {
1047 return !fHasError && fUnion.minMaxInt.fMinInt == -1;
1048 }
1049
1050 UBool copyErrorTo(UErrorCode &status) const {
1051 if (fHasError) {
1052 status = fUnion.errorCode;
1053 return true;
1054 }
1055 return false;
1056 }
1057
1058 void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const;
1059
1060 bool operator==(const IntegerWidth& other) const;
1061
1062 // To allow MacroProps/MicroProps to initialize empty instances:
1063 friend struct impl::MacroProps;
1064 friend struct impl::MicroProps;
1065
1066 // To allow NumberFormatterImpl to access isBogus():
1067 friend class impl::NumberFormatterImpl;
1068
1069 // To allow the use of this class when formatting:
1070 friend class impl::MutablePatternModifier;
1071 friend class impl::ImmutablePatternModifier;
1072
1073 // So that NumberPropertyMapper can create instances
1074 friend class impl::NumberPropertyMapper;
1075
1076 // To allow access to the skeleton generation code:
1077 friend class impl::GeneratorHelpers;
1078};
1079
1088class U_I18N_API Scale : public UMemory {
1089 public:
1096 static Scale none();
1097
1109
1123
1133
1141
1142 // We need a custom destructor for the DecNum, which means we need to declare
1143 // the copy/move constructor/assignment quartet.
1144
1147
1150
1152 Scale(Scale&& src) noexcept;
1153
1155 Scale& operator=(Scale&& src) noexcept;
1156
1159
1160#ifndef U_HIDE_INTERNAL_API
1163#endif /* U_HIDE_INTERNAL_API */
1164
1165 private:
1166 int32_t fMagnitude;
1167 impl::DecNum* fArbitrary;
1168 UErrorCode fError;
1169
1170 Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {}
1171
1172 Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {}
1173
1174 bool isValid() const {
1175 return fMagnitude != 0 || fArbitrary != nullptr;
1176 }
1177
1178 UBool copyErrorTo(UErrorCode &status) const {
1179 if (U_FAILURE(fError)) {
1180 status = fError;
1181 return true;
1182 }
1183 return false;
1184 }
1185
1186 void applyTo(impl::DecimalQuantity& quantity) const;
1187
1188 void applyReciprocalTo(impl::DecimalQuantity& quantity) const;
1189
1190 // To allow MacroProps/MicroProps to initialize empty instances:
1191 friend struct impl::MacroProps;
1192 friend struct impl::MicroProps;
1193
1194 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1195 friend class impl::NumberFormatterImpl;
1196
1197 // To allow the helper class MultiplierFormatHandler access to private fields:
1198 friend class impl::MultiplierFormatHandler;
1199
1200 // To allow access to the skeleton generation code:
1201 friend class impl::GeneratorHelpers;
1202
1203 // To allow access to parsing code:
1204 friend class ::icu::numparse::impl::NumberParserImpl;
1205 friend class ::icu::numparse::impl::MultiplierParseHandler;
1206};
1207
1208namespace impl {
1209
1210// Do not enclose entire StringProp with #ifndef U_HIDE_INTERNAL_API, needed for a protected field.
1211// And do not enclose its class boilerplate within #ifndef U_HIDE_INTERNAL_API.
1217
1218 public:
1221
1224
1227
1228#ifndef U_HIDE_INTERNAL_API
1229
1232
1235
1237 int16_t length() const {
1238 return fLength;
1239 }
1240
1244 void set(StringPiece value);
1245
1247 bool isSet() const {
1248 return fLength > 0;
1249 }
1250
1251#endif // U_HIDE_INTERNAL_API
1252
1253 private:
1254 char *fValue;
1255 int16_t fLength;
1256 UErrorCode fError;
1257
1258 StringProp() : fValue(nullptr), fLength(0), fError(U_ZERO_ERROR) {
1259 }
1260
1262 UBool copyErrorTo(UErrorCode &status) const {
1263 if (U_FAILURE(fError)) {
1264 status = fError;
1265 return true;
1266 }
1267 return false;
1268 }
1269
1270 // Allow NumberFormatterImpl to access fValue.
1271 friend class impl::NumberFormatterImpl;
1272
1273 // Allow skeleton generation code to access private members.
1274 friend class impl::GeneratorHelpers;
1275
1276 // Allow MacroProps/MicroProps to initialize empty instances and to call
1277 // copyErrorTo().
1278 friend struct impl::MacroProps;
1279};
1280
1281// Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1284 public:
1286 SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {}
1287
1290
1293
1296
1299
1302
1303#ifndef U_HIDE_INTERNAL_API
1304
1309 void setTo(const DecimalFormatSymbols &dfs);
1310
1315 void setTo(const NumberingSystem *ns);
1316
1322
1327 bool isNumberingSystem() const;
1328
1334
1340
1341#endif // U_HIDE_INTERNAL_API
1342
1345 if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) {
1347 return true;
1348 } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) {
1350 return true;
1351 }
1352 return false;
1353 }
1354
1355 private:
1356 enum SymbolsPointerType {
1357 SYMPTR_NONE, SYMPTR_DFS, SYMPTR_NS
1358 } fType;
1359
1360 union {
1361 const DecimalFormatSymbols *dfs;
1362 const NumberingSystem *ns;
1363 } fPtr;
1364
1365 void doCopyFrom(const SymbolsWrapper &other);
1366
1367 void doMoveFrom(SymbolsWrapper&& src);
1368
1369 void doCleanup();
1370};
1371
1372// Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1375 public:
1376#ifndef U_HIDE_INTERNAL_API
1379
1385
1386 // Future: static Grouper forProperties(DecimalFormatProperties& properties);
1387
1390 : fGrouping1(grouping1),
1391 fGrouping2(grouping2),
1392 fMinGrouping(minGrouping),
1393 fStrategy(strategy) {}
1394
1397
1400#endif // U_HIDE_INTERNAL_API
1401
1402 private:
1411 int16_t fGrouping1;
1412 int16_t fGrouping2;
1413
1421 int16_t fMinGrouping;
1422
1427 UNumberGroupingStrategy fStrategy;
1428
1429 Grouper() : fGrouping1(-3) {}
1430
1431 bool isBogus() const {
1432 return fGrouping1 == -3;
1433 }
1434
1436 void setLocaleData(const impl::ParsedPatternInfo &patternInfo, const Locale& locale);
1437
1438 bool groupAtPosition(int32_t position, const impl::DecimalQuantity &value) const;
1439
1440 // To allow MacroProps/MicroProps to initialize empty instances:
1441 friend struct MacroProps;
1442 friend struct MicroProps;
1443 friend struct SimpleMicroProps;
1444
1445 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1446 friend class NumberFormatterImpl;
1447 friend class ::icu::number::SimpleNumberFormatter;
1448
1449 // To allow NumberParserImpl to perform setLocaleData():
1450 friend class ::icu::numparse::impl::NumberParserImpl;
1451
1452 // To allow access to the skeleton generation code:
1453 friend class impl::GeneratorHelpers;
1454};
1455
1456// Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1458class U_I18N_API Padder : public UMemory {
1459 public:
1460#ifndef U_HIDE_INTERNAL_API
1462 static Padder none();
1463
1466
1469#endif // U_HIDE_INTERNAL_API
1470
1471 private:
1472 UChar32 fWidth; // -3 = error; -2 = bogus; -1 = no padding
1473 union {
1474 struct {
1475 int32_t fCp;
1476 UNumberFormatPadPosition fPosition;
1477 } padding;
1478 UErrorCode errorCode;
1479 } fUnion;
1480
1482
1483 Padder(int32_t width);
1484
1485 Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT
1486 fUnion.errorCode = errorCode;
1487 }
1488
1489 Padder() : fWidth(-2) {} // NOLINT
1490
1491 bool isBogus() const {
1492 return fWidth == -2;
1493 }
1494
1495 UBool copyErrorTo(UErrorCode &status) const {
1496 if (fWidth == -3) {
1497 status = fUnion.errorCode;
1498 return true;
1499 }
1500 return false;
1501 }
1502
1503 bool isValid() const {
1504 return fWidth > 0;
1505 }
1506
1507 int32_t padAndApply(const impl::Modifier &mod1, const impl::Modifier &mod2,
1508 FormattedStringBuilder &string, int32_t leftIndex, int32_t rightIndex,
1509 UErrorCode &status) const;
1510
1511 // To allow MacroProps/MicroProps to initialize empty instances:
1512 friend struct MacroProps;
1513 friend struct MicroProps;
1514
1515 // To allow NumberFormatterImpl to access isBogus() and perform other operations:
1516 friend class impl::NumberFormatterImpl;
1517
1518 // To allow access to the skeleton generation code:
1519 friend class impl::GeneratorHelpers;
1520};
1521
1522// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
1527
1529 MeasureUnit unit; // = MeasureUnit(); (the base dimensionless unit)
1530
1532 MeasureUnit perUnit; // = MeasureUnit(); (the base dimensionless unit)
1533
1535 Precision precision; // = Precision(); (bogus)
1536
1539
1541 Grouper grouper; // = Grouper(); (bogus)
1542
1544 Padder padder; // = Padder(); (bogus)
1545
1547 IntegerWidth integerWidth; // = IntegerWidth(); (bogus)
1548
1551
1552 // UNUM_XYZ_COUNT denotes null (bogus) values.
1553
1556
1559
1561 bool approximately = false;
1562
1565
1567 Scale scale; // = Scale(); (benign value)
1568
1570 StringProp usage; // = StringProp(); (no usage)
1571
1573 StringProp unitDisplayCase; // = StringProp(); (nominative)
1574
1576 const AffixPatternProvider* affixProvider = nullptr; // no ownership
1577
1579 const PluralRules* rules = nullptr; // no ownership
1580
1582 int32_t threshold = kInternalDefaultThreshold;
1583
1586
1587 // NOTE: Uses default copy and move constructors.
1588
1594 return notation.copyErrorTo(status) || precision.copyErrorTo(status) ||
1595 padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) ||
1596 symbols.copyErrorTo(status) || scale.copyErrorTo(status) || usage.copyErrorTo(status) ||
1597 unitDisplayCase.copyErrorTo(status);
1598 }
1599};
1600
1601} // namespace impl
1602
1603#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
1604// Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method
1605// is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation
1606// inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is
1607// fully defined. However, since each translation unit explicitly instantiates all the necessary template classes,
1608// they will all be passed to the linker, and the linker will still find and export all the class members.
1609#pragma warning(push)
1610#pragma warning(disable: 4661)
1611#endif
1612
1618template<typename Derived>
1620 public:
1649 Derived notation(const Notation &notation) const &;
1650
1660 Derived notation(const Notation &notation) &&;
1661
1710 Derived unit(const icu::MeasureUnit &unit) const &;
1711
1722
1737
1748
1771 Derived perUnit(const icu::MeasureUnit &perUnit) const &;
1772
1783
1798
1809
1840 Derived precision(const Precision& precision) const &;
1841
1851 Derived precision(const Precision& precision) &&;
1852
1872
1882
1911
1922
1948
1959
2000 Derived symbols(const DecimalFormatSymbols &symbols) const &;
2001
2012
2047
2058
2085
2096
2123
2134
2161
2172
2197 Derived scale(const Scale &scale) const &;
2198
2208 Derived scale(const Scale &scale) &&;
2209
2252 Derived usage(StringPiece usage) const &;
2253
2262
2271 Derived displayOptions(const DisplayOptions &displayOptions) const &;
2272
2280 Derived displayOptions(const DisplayOptions &displayOptions) &&;
2281
2282#ifndef U_HIDE_INTERNAL_API
2293 Derived unitDisplayCase(StringPiece unitDisplayCase) const &;
2294
2305#endif // U_HIDE_INTERNAL_API
2306
2307#ifndef U_HIDE_INTERNAL_API
2308
2314 Derived padding(const impl::Padder &padder) const &;
2315
2317 Derived padding(const impl::Padder &padder) &&;
2318
2325 Derived threshold(int32_t threshold) const &;
2326
2329
2335 Derived macros(const impl::MacroProps& macros) const &;
2336
2339
2342
2345
2346#endif /* U_HIDE_INTERNAL_API */
2347
2366
2379
2388
2395 UBool copyErrorTo(UErrorCode &outErrorCode) const {
2396 if (U_FAILURE(outErrorCode)) {
2397 // Do not overwrite the older error code
2398 return true;
2399 }
2400 fMacros.copyErrorTo(outErrorCode);
2401 return U_FAILURE(outErrorCode);
2402 }
2403
2404 // NOTE: Uses default copy and move constructors.
2405
2406 private:
2407 impl::MacroProps fMacros;
2408
2409 // Don't construct me directly! Use (Un)LocalizedNumberFormatter.
2410 NumberFormatterSettings() = default;
2411
2412 friend class LocalizedNumberFormatter;
2413 friend class UnlocalizedNumberFormatter;
2414
2415 // Give NumberRangeFormatter access to the MacroProps
2416 friend void impl::touchRangeLocales(impl::RangeMacroProps& macros);
2417 friend class impl::NumberRangeFormatterImpl;
2418};
2419
2420// Explicit instantiations in source/i18n/number_fluent.cpp.
2421// (MSVC treats imports/exports of explicit instantiations differently.)
2422#ifndef _MSC_VER
2425#endif
2426
2437
2438 public:
2449
2460
2467
2473
2480
2486
2493
2494 private:
2496
2499
2500 // To give the fluent setters access to this class's constructor:
2502
2503 // To give NumberFormatter::with() access to this class's constructor:
2504 friend class NumberFormatter;
2505};
2506
2517 public:
2530
2543
2559
2560#ifndef U_HIDE_INTERNAL_API
2561
2562
2567
2571 FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const;
2572
2577
2582 const impl::NumberFormatterImpl* getCompiled() const;
2583
2589
2590#endif /* U_HIDE_INTERNAL_API */
2591
2606
2613
2619
2626
2632
2639
2640#ifndef U_HIDE_INTERNAL_API
2641
2654 void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const;
2655
2656#endif /* U_HIDE_INTERNAL_API */
2657
2663
2664 private:
2665 // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal
2666 // header, and LocalPointer needs the full class definition in order to delete the instance.
2667 const impl::NumberFormatterImpl* fCompiled {nullptr};
2668 char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t
2669
2670 // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter
2671 // from a DecimalFormat.
2672 const impl::DecimalFormatWarehouse* fWarehouse {nullptr};
2673
2674 explicit LocalizedNumberFormatter(const NumberFormatterSettings<LocalizedNumberFormatter>& other);
2675
2676 explicit LocalizedNumberFormatter(NumberFormatterSettings<LocalizedNumberFormatter>&& src) noexcept;
2677
2678 LocalizedNumberFormatter(const impl::MacroProps &macros, const Locale &locale);
2679
2680 LocalizedNumberFormatter(impl::MacroProps &&macros, const Locale &locale);
2681
2682 void resetCompiled();
2683
2684 void lnfMoveHelper(LocalizedNumberFormatter&& src);
2685
2686 void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status);
2687
2691 bool computeCompiled(UErrorCode& status) const;
2692
2693 // To give the fluent setters access to this class's constructor:
2694 friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
2695 friend class NumberFormatterSettings<LocalizedNumberFormatter>;
2696
2697 // To give UnlocalizedNumberFormatter::locale() access to this class's constructor:
2698 friend class UnlocalizedNumberFormatter;
2699};
2700
2701#if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
2702// Warning 4661.
2703#pragma warning(pop)
2704#endif
2705
2780
2781} // namespace number
2783
2784#endif /* #if !UCONFIG_NO_FORMATTING */
2785
2786#endif /* U_SHOW_CPLUSPLUS_API */
2787
2788#endif // __NUMBERFORMATTER_H__
C++ API: Appendable class: Sink for Unicode code points and 16-bit code units (char16_ts).
C++ API: Interface for writing bytes, and implementation classes.
A unit of currency, such as USD (U.S.
Definition currunit.h:39
This class represents the set of symbols needed by DecimalFormat to format numbers.
Definition dcfmtsym.h:86
Represents all the display options that are supported by CLDR such as grammatical case,...
Base class for all formats.
Definition format.h:98
"Smart pointer" base class; do not use directly: use LocalPointer etc.
"Smart pointer" class, deletes objects via the standard C++ delete operator.
A Locale object represents a specific geographical, political, or cultural region.
Definition locid.h:195
A unit such as length, mass, volume, currency, etc.
Definition measunit.h:369
Defines numbering systems.
Definition numsys.h:60
Defines rules for mapping non-negative numeric values onto a small set of keywords.
Definition plurrule.h:212
A string-like object that points to a sized piece of memory.
Definition stringpiece.h:60
UMemory is the common ICU base class.
Definition uobject.h:115
UnicodeString is a string class that stores Unicode characters directly and provides similar function...
Definition unistr.h:296
A class that defines a rounding precision parameterized by a currency to be used when formatting numb...
Precision withCurrency(const CurrencyUnit &currency) const
Associates a currency with this rounding precision.
The result of a number formatting operation.
A class that defines a rounding precision based on a number of fraction places and optionally signifi...
Precision withMinDigits(int32_t minSignificantDigits) const
Ensure that no less than this number of significant digits are retained when rounding according to fr...
Precision withSignificantDigits(int32_t minSignificantDigits, int32_t maxSignificantDigits, UNumberRoundingPriority priority) const
Override maximum fraction digits with maximum significant digits depending on the magnitude of the nu...
Precision withMaxDigits(int32_t maxSignificantDigits) const
Ensure that no more than this number of significant digits are retained when rounding according to fr...
A class that defines a rounding precision parameterized by a rounding increment to be used when forma...
Precision withMinFraction(int32_t minFrac) const
Specifies the minimum number of fraction digits to render after the decimal separator,...
A class that defines the strategy for padding and truncating integers before the decimal separator.
static IntegerWidth zeroFillTo(int32_t minInt)
Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal ...
IntegerWidth truncateAt(int32_t maxInt)
Truncate numbers exceeding a certain number of numerals before the decimal separator.
A NumberFormatter that has a locale associated with it; this means .format() methods are available.
LocalizedNumberFormatter(LocalizedNumberFormatter &&src) noexcept
Move constructor: The source LocalizedNumberFormatter will be left in a valid but undefined state.
Format * toFormat(UErrorCode &status) const
Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use of this nu...
const DecimalFormatSymbols * getDecimalFormatSymbols() const
FormattedNumber formatInt(int64_t value, UErrorCode &status) const
Format the given integer number to a string using the settings specified in the NumberFormatter fluen...
LocalizedNumberFormatter()=default
Default constructor: puts the formatter into a valid but undefined state.
LocalizedNumberFormatter(const LocalizedNumberFormatter &other)
Returns a copy of this LocalizedNumberFormatter.
const impl::NumberFormatterImpl * getCompiled() const
Internal method for testing.
int32_t getCallCount() const
Internal method for testing.
~LocalizedNumberFormatter()
Destruct this LocalizedNumberFormatter, cleaning up any memory it might own.
LocalizedNumberFormatter & operator=(LocalizedNumberFormatter &&src) noexcept
Move assignment operator: The source LocalizedNumberFormatter will be left in a valid but undefined s...
void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const
This is the core entrypoint to the number formatting pipeline.
FormattedNumber formatDecimal(StringPiece value, UErrorCode &status) const
Format the given decimal number to a string using the settings specified in the NumberFormatter fluen...
void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString &result, UErrorCode &status) const
Internal method for DecimalFormat compatibility.
FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity &dq, UErrorCode &status) const
Internal method.
FormattedNumber formatDouble(double value, UErrorCode &status) const
Format the given float or double to a string using the settings specified in the NumberFormatter flue...
LocalizedNumberFormatter & operator=(const LocalizedNumberFormatter &other)
Copy assignment operator.
A class that defines the notation style to be used when formatting numbers in NumberFormatter.
static CompactNotation compactShort()
Print the number using short-form compact notation.
static ScientificNotation engineering()
Print the number using engineering notation, a variant of scientific notation in which the exponent m...
static CompactNotation compactLong()
Print the number using long-form compact notation.
static SimpleNotation simple()
Print the number using simple notation without any scaling by powers of ten.
static ScientificNotation scientific()
Print the number using scientific notation (also known as scientific form, standard index form,...
An abstract base class for specifying settings related to number formatting.
Derived unitDisplayCase(StringPiece unitDisplayCase) &&
NOTE: Use displayOptions instead.
LocalPointer< Derived > clone() const &
Returns the current (Un)LocalizedNumberFormatter as a LocalPointer wrapping a heap-allocated copy of ...
Derived adoptSymbols(NumberingSystem *symbols) const &
Specifies that the given numbering system should be used when fetching symbols.
Derived precision(const Precision &precision) const &
Specifies the rounding precision to use when formatting numbers.
Derived decimal(UNumberDecimalSeparatorDisplay style) &&
Overload of decimal() for use on an rvalue reference.
Derived unitWidth(UNumberUnitWidth width) const &
Sets the width of the unit (measure unit or currency).
Derived adoptUnit(icu::MeasureUnit *unit) const &
Like unit(), but takes ownership of a pointer.
Derived perUnit(const icu::MeasureUnit &perUnit) &&
Overload of perUnit() for use on an rvalue reference.
Derived padding(const impl::Padder &padder) &&
Derived adoptSymbols(NumberingSystem *symbols) &&
Overload of adoptSymbols() for use on an rvalue reference.
Derived macros(const impl::MacroProps &macros) &&
Derived roundingMode(UNumberFormatRoundingMode roundingMode) &&
Overload of roundingMode() for use on an rvalue reference.
Derived integerWidth(const IntegerWidth &style) const &
Specifies the minimum and maximum number of digits to render before the decimal mark.
Derived macros(const impl::MacroProps &macros) const &
Internal fluent setter to overwrite the entire macros object.
Derived threshold(int32_t threshold) const &
Internal fluent setter to support a custom regulation threshold.
Derived perUnit(const icu::MeasureUnit &perUnit) const &
Sets a unit to be used in the denominator.
Derived integerWidth(const IntegerWidth &style) &&
Overload of integerWidth() for use on an rvalue reference.
Derived unitDisplayCase(StringPiece unitDisplayCase) const &
NOTE: Use displayOptions instead.
Derived grouping(UNumberGroupingStrategy strategy) const &
Specifies the grouping strategy to use when formatting numbers.
Derived unit(const icu::MeasureUnit &unit) const &
Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers.
Derived displayOptions(const DisplayOptions &displayOptions) const &
Specifies the DisplayOptions.
Derived usage(StringPiece usage) &&
Overload of usage() for use on an rvalue reference.
Derived displayOptions(const DisplayOptions &displayOptions) &&
Overload of displayOptions() for use on an rvalue reference.
Derived adoptPerUnit(icu::MeasureUnit *perUnit) const &
Like perUnit(), but takes ownership of a pointer.
Derived adoptUnit(icu::MeasureUnit *unit) &&
Overload of adoptUnit() for use on an rvalue reference.
Derived scale(const Scale &scale) &&
Overload of scale() for use on an rvalue reference.
Derived precision(const Precision &precision) &&
Overload of precision() for use on an rvalue reference.
Derived symbols(const DecimalFormatSymbols &symbols) &&
Overload of symbols() for use on an rvalue reference.
Derived padding(const impl::Padder &padder) const &
Set the padding strategy.
Derived notation(const Notation &notation) const &
Specifies the notation style (simple, scientific, or compact) for rendering numbers.
Derived sign(UNumberSignDisplay style) const &
Sets the plus/minus sign display strategy.
Derived threshold(int32_t threshold) &&
Derived roundingMode(UNumberFormatRoundingMode roundingMode) const &
Specifies how to determine the direction to round a number when it has more digits than fit in the de...
Derived symbols(const DecimalFormatSymbols &symbols) const &
Specifies the symbols (decimal separator, grouping separator, percent sign, numerals,...
Derived macros(impl::MacroProps &&macros) &&
Derived sign(UNumberSignDisplay style) &&
Overload of sign() for use on an rvalue reference.
UnicodeString toSkeleton(UErrorCode &status) const
Creates a skeleton string representation of this number formatter.
Derived grouping(UNumberGroupingStrategy strategy) &&
Overload of grouping() for use on an rvalue reference.
Derived usage(StringPiece usage) const &
Specifies the usage for which numbers will be formatted ("person-height", "road", "rainfall",...
Derived adoptPerUnit(icu::MeasureUnit *perUnit) &&
Overload of adoptPerUnit() for use on an rvalue reference.
Derived unitWidth(UNumberUnitWidth width) &&
Overload of unitWidth() for use on an rvalue reference.
Derived decimal(UNumberDecimalSeparatorDisplay style) const &
Sets the decimal separator display strategy.
Derived unit(const icu::MeasureUnit &unit) &&
Overload of unit() for use on an rvalue reference.
Derived macros(impl::MacroProps &&macros) const &
Derived scale(const Scale &scale) const &
Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting.
Derived notation(const Notation &notation) &&
Overload of notation() for use on an rvalue reference.
See the main description in numberformatter.h for documentation and examples.
static UnlocalizedNumberFormatter forSkeleton(const UnicodeString &skeleton, UParseError &perror, UErrorCode &status)
Call this method at the beginning of a NumberFormatter fluent chain to create an instance based on a ...
static UnlocalizedNumberFormatter forSkeleton(const UnicodeString &skeleton, UErrorCode &status)
Call this method at the beginning of a NumberFormatter fluent chain to create an instance based on a ...
static UnlocalizedNumberFormatter with()
Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not curren...
NumberFormatter()=delete
Use factory methods instead of the constructor to create a NumberFormatter.
static LocalizedNumberFormatter withLocale(const Locale &locale)
Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at t...
A class that defines the rounding precision to be used when formatting numbers in NumberFormatter.
static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits)
Show numbers rounded if necessary to a certain number of significant digits/figures.
static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces)
Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal ...
static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits)
Always show at least a certain number of significant digits/figures, padding with zeros if necessary.
static FractionPrecision maxFraction(int32_t maxFractionPlaces)
Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal ...
static IncrementPrecision increment(double roundingIncrement)
Show numbers rounded if necessary to the closest multiple of a certain rounding increment.
static CurrencyPrecision currency(UCurrencyUsage currencyUsage)
Show numbers rounded and padded according to the rules for the currency unit.
static FractionPrecision minFraction(int32_t minFractionPlaces)
Always show at least a certain number of fraction places after the decimal separator,...
Precision trailingZeroDisplay(UNumberTrailingZeroDisplay trailingZeroDisplay) const
Configure how trailing zeros are displayed on numbers.
static Precision unlimited()
Show all available digits to full precision.
static FractionPrecision integer()
Show numbers rounded if necessary to the nearest integer.
static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits)
Show numbers rounded if necessary to a certain number of significant digits or significant figures.
static IncrementPrecision incrementExact(uint64_t mantissa, int16_t magnitude)
Version of Precision::increment() that takes an integer at a particular power of 10.
static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces)
Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal ...
static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits, int32_t maxSignificantDigits)
Show numbers rounded if necessary to a certain number of significant digits/figures; in addition,...
A class that defines a quantity by which a number should be multiplied when formatting.
static Scale none()
Do not change the value of numbers when formatting or parsing.
static Scale powerOfTen(int32_t power)
Multiply numbers by a power of ten before formatting.
Scale(const Scale &other)
static Scale byDoubleAndPowerOfTen(double multiplicand, int32_t power)
Multiply a number by both a power of ten and by an arbitrary double value.
static Scale byDecimal(StringPiece multiplicand)
Multiply numbers by an arbitrary value before formatting.
Scale(int32_t magnitude, impl::DecNum *arbitraryToAdopt)
Scale & operator=(const Scale &other)
Scale(Scale &&src) noexcept
Scale & operator=(Scale &&src) noexcept
static Scale byDouble(double multiplicand)
Multiply numbers by an arbitrary value before formatting.
A class that defines the scientific notation style to be used when formatting numbers in NumberFormat...
ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const
Sets whether to show the sign on positive and negative exponents in scientific notation.
ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const
Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros ...
A NumberFormatter that does not yet have a locale.
UnlocalizedNumberFormatter & operator=(UnlocalizedNumberFormatter &&src) noexcept
Move assignment operator: The source UnlocalizedNumberFormatter will be left in a valid but undefined...
UnlocalizedNumberFormatter()=default
Default constructor: puts the formatter into a valid but undefined state.
UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other)
Returns a copy of this UnlocalizedNumberFormatter.
LocalizedNumberFormatter locale(const icu::Locale &locale) &&
Overload of locale() for use on an rvalue reference.
UnlocalizedNumberFormatter & operator=(const UnlocalizedNumberFormatter &other)
Copy assignment operator.
UnlocalizedNumberFormatter(UnlocalizedNumberFormatter &&src) noexcept
Move constructor: The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
LocalizedNumberFormatter locale(const icu::Locale &locale) const &
Associate the given locale with the number formatter.
static Grouper forStrategy(UNumberGroupingStrategy grouping)
Grouper(int16_t grouping1, int16_t grouping2, int16_t minGrouping, UNumberGroupingStrategy strategy)
int16_t getSecondary() const
static Grouper forProperties(const DecimalFormatProperties &properties)
Resolve the values in Properties to a Grouper object.
int16_t getPrimary() const
static Padder forProperties(const DecimalFormatProperties &properties)
static Padder codePoints(UChar32 cp, int32_t targetWidth, UNumberFormatPadPosition position)
Manages NumberFormatterSettings::usage()'s char* instance on the heap.
StringProp(StringProp &&src) noexcept
StringProp(const StringProp &other)
StringProp & operator=(StringProp &&src) noexcept
StringProp & operator=(const StringProp &other)
void set(StringPiece value)
SymbolsWrapper & operator=(SymbolsWrapper &&src) noexcept
SymbolsWrapper & operator=(const SymbolsWrapper &other)
bool isNumberingSystem() const
Whether the object is currently holding a NumberingSystem.
const DecimalFormatSymbols * getDecimalFormatSymbols() const
Get the DecimalFormatSymbols pointer.
SymbolsWrapper(const SymbolsWrapper &other)
SymbolsWrapper(SymbolsWrapper &&src) noexcept
void setTo(const DecimalFormatSymbols &dfs)
The provided object is copied, but we do not adopt it.
const NumberingSystem * getNumberingSystem() const
Get the NumberingSystem pointer.
void setTo(const NumberingSystem *ns)
Adopt the provided object.
UBool copyErrorTo(UErrorCode &status) const
bool isDecimalFormatSymbols() const
Whether the object is currently holding a DecimalFormatSymbols.
C++ API: Currency Unit Information.
C++ API: Symbols for formatting numbers.
C++ API: Display options class.
C++ API: FieldPosition identifies the fields in a formatted output.
C API: Formatted number result from various number formatting functions.
C++ API: FieldPosition Iterator.
C++ API: A unit for measuring a quantity.
U_EXPORT UBool operator==(const StringPiece &x, const StringPiece &y)
Global operator == for StringPiece.
C++ API: units for percent and permille.
void touchRangeLocales(impl::RangeMacroProps &macros)
Used for NumberRangeFormatter and implemented in numrange_fluent.cpp.
C API: Parse Error Information.
C++ API: PluralRules object.
A UParseError struct is used to returned detailed information about parsing errors.
Definition parseerr.h:58
bool fRetain
Whether to retain trailing zeros based on the looser strategy.
bool copyErrorTo(UErrorCode &status) const
Check all members for errors.
C API: Encapsulates information about a currency.
UCurrencyUsage
Currency Usage used for Decimal Format.
Definition ucurr.h:41
int32_t UChar32
Define UChar32 as a type for single Unicode code points.
Definition umachine.h:435
int8_t UBool
The ICU boolean type, a signed-byte integer.
Definition umachine.h:247
C API: Compatibility APIs for number formatting.
UNumberCompactStyle
Constants for specifying short or long format.
Definition unum.h:289
UNumberFormatPadPosition
The possible number format pad positions.
Definition unum.h:278
C API: Localized number formatting; not recommended for C++.
UNumberRoundingPriority
An enum declaring how to resolve conflicts between maximum fraction digits and maximum significant di...
UNumberSignDisplay
An enum declaring how to denote positive and negative numbers.
@ UNUM_SIGN_COUNT
One more than the highest UNumberSignDisplay value.
UNumberDecimalSeparatorDisplay
An enum declaring how to render the decimal separator.
@ UNUM_DECIMAL_SEPARATOR_COUNT
One more than the highest UNumberDecimalSeparatorDisplay value.
UNumberTrailingZeroDisplay
An enum declaring how to render trailing zeros.
@ UNUM_TRAILING_ZERO_AUTO
Display trailing zeros according to the settings for minimum fraction and significant digits.
UNumberUnitWidth
An enum declaring how to render units, including currencies.
@ UNUM_UNIT_WIDTH_COUNT
One more than the highest UNumberUnitWidth value.
C API: Header-only input options for various number formatting APIs.
UNumberFormatRoundingMode
The possible number format rounding modes.
@ UNUM_ROUND_HALFEVEN
Half-even rounding.
UNumberGroupingStrategy
An enum declaring the strategy for when and how to display grouping separators (i....
C++ API: Common ICU base class UObject.
Basic definitions for ICU, for both C and C++ APIs.
UErrorCode
Standard ICU4C error code type, a substitute for exceptions.
Definition utypes.h:415
@ U_MEMORY_ALLOCATION_ERROR
Memory allocation error.
Definition utypes.h:457
@ U_ZERO_ERROR
No error, no warning.
Definition utypes.h:449
#define U_FAILURE(x)
Does the error code indicate a failure?
Definition utypes.h:717
#define U_I18N_API
Set to export library symbols from inside the i18n library, and to import them from outside.
Definition utypes.h:301