numberformatter.h 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787
  1. // © 2017 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. #ifndef __NUMBERFORMATTER_H__
  4. #define __NUMBERFORMATTER_H__
  5. #include "unicode/utypes.h"
  6. #if U_SHOW_CPLUSPLUS_API
  7. #if !UCONFIG_NO_FORMATTING
  8. #include "unicode/appendable.h"
  9. #include "unicode/bytestream.h"
  10. #include "unicode/currunit.h"
  11. #include "unicode/dcfmtsym.h"
  12. #include "unicode/displayoptions.h"
  13. #include "unicode/fieldpos.h"
  14. #include "unicode/fpositer.h"
  15. #include "unicode/measunit.h"
  16. #include "unicode/nounit.h"
  17. #include "unicode/parseerr.h"
  18. #include "unicode/plurrule.h"
  19. #include "unicode/ucurr.h"
  20. #include "unicode/unum.h"
  21. #include "unicode/unumberformatter.h"
  22. #include "unicode/uobject.h"
  23. #include "unicode/unumberoptions.h"
  24. #include "unicode/formattednumber.h"
  25. /**
  26. * \file
  27. * \brief C++ API: All-in-one formatter for localized numbers, currencies, and units.
  28. *
  29. * For a full list of options, see icu::number::NumberFormatterSettings.
  30. *
  31. * <pre>
  32. * // Most basic usage:
  33. * NumberFormatter::withLocale(...).format(123).toString(); // 1,234 in en-US
  34. *
  35. * // Custom notation, unit, and rounding precision:
  36. * NumberFormatter::with()
  37. * .notation(Notation::compactShort())
  38. * .unit(CurrencyUnit("EUR", status))
  39. * .precision(Precision::maxDigits(2))
  40. * .locale(...)
  41. * .format(1234)
  42. * .toString(); // €1.2K in en-US
  43. *
  44. * // Create a formatter in a singleton by value for use later:
  45. * static const LocalizedNumberFormatter formatter = NumberFormatter::withLocale(...)
  46. * .unit(NoUnit::percent())
  47. * .precision(Precision::fixedFraction(3));
  48. * formatter.format(5.9831).toString(); // 5.983% in en-US
  49. *
  50. * // Create a "template" in a singleton unique_ptr but without setting a locale until the call site:
  51. * std::unique_ptr<UnlocalizedNumberFormatter> template = NumberFormatter::with()
  52. * .sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
  53. * .unit(MeasureUnit::getMeter())
  54. * .unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
  55. * .clone();
  56. * template->locale(...).format(1234).toString(); // +1,234 meters in en-US
  57. * </pre>
  58. *
  59. * <p>
  60. * This API offers more features than DecimalFormat and is geared toward new users of ICU.
  61. *
  62. * <p>
  63. * NumberFormatter instances (i.e., LocalizedNumberFormatter and UnlocalizedNumberFormatter)
  64. * are immutable and thread safe. This means that invoking a configuration method has no
  65. * effect on the receiving instance; you must store and use the new number formatter instance it returns instead.
  66. *
  67. * <pre>
  68. * UnlocalizedNumberFormatter formatter = UnlocalizedNumberFormatter::with().notation(Notation::scientific());
  69. * formatter.precision(Precision.maxFraction(2)); // does nothing!
  70. * formatter.locale(Locale.getEnglish()).format(9.8765).toString(); // prints "9.8765E0", not "9.88E0"
  71. * </pre>
  72. *
  73. * <p>
  74. * This API is based on the <em>fluent</em> design pattern popularized by libraries such as Google's Guava. For
  75. * extensive details on the design of this API, read <a href="https://goo.gl/szi5VB">the design doc</a>.
  76. *
  77. * @author Shane Carr
  78. */
  79. U_NAMESPACE_BEGIN
  80. // Forward declarations:
  81. class IFixedDecimal;
  82. class FieldPositionIteratorHandler;
  83. class FormattedStringBuilder;
  84. namespace numparse {
  85. namespace impl {
  86. // Forward declarations:
  87. class NumberParserImpl;
  88. class MultiplierParseHandler;
  89. }
  90. }
  91. namespace units {
  92. // Forward declarations:
  93. class UnitsRouter;
  94. } // namespace units
  95. namespace number { // icu::number
  96. // Forward declarations:
  97. class UnlocalizedNumberFormatter;
  98. class LocalizedNumberFormatter;
  99. class SimpleNumberFormatter;
  100. class FormattedNumber;
  101. class Notation;
  102. class ScientificNotation;
  103. class Precision;
  104. class FractionPrecision;
  105. class CurrencyPrecision;
  106. class IncrementPrecision;
  107. class IntegerWidth;
  108. namespace impl {
  109. // can't be #ifndef U_HIDE_INTERNAL_API; referenced throughout this file in public classes
  110. /**
  111. * Datatype for minimum/maximum fraction digits. Must be able to hold kMaxIntFracSig.
  112. *
  113. * @internal
  114. */
  115. typedef int16_t digits_t;
  116. // can't be #ifndef U_HIDE_INTERNAL_API; needed for struct initialization
  117. /**
  118. * Use a default threshold of 3. This means that the third time .format() is called, the data structures get built
  119. * using the "safe" code path. The first two calls to .format() will trigger the unsafe code path.
  120. *
  121. * @internal
  122. */
  123. static constexpr int32_t kInternalDefaultThreshold = 3;
  124. // Forward declarations:
  125. class Padder;
  126. struct MacroProps;
  127. struct MicroProps;
  128. class DecimalQuantity;
  129. class UFormattedNumberData;
  130. class NumberFormatterImpl;
  131. struct ParsedPatternInfo;
  132. class ScientificModifier;
  133. class MultiplierProducer;
  134. class RoundingImpl;
  135. class ScientificHandler;
  136. class Modifier;
  137. class AffixPatternProvider;
  138. class NumberPropertyMapper;
  139. struct DecimalFormatProperties;
  140. class MultiplierFormatHandler;
  141. class CurrencySymbols;
  142. class GeneratorHelpers;
  143. class DecNum;
  144. class NumberRangeFormatterImpl;
  145. struct RangeMacroProps;
  146. struct UFormattedNumberImpl;
  147. class MutablePatternModifier;
  148. class ImmutablePatternModifier;
  149. struct DecimalFormatWarehouse;
  150. struct SimpleMicroProps;
  151. class AdoptingSignumModifierStore;
  152. /**
  153. * Used for NumberRangeFormatter and implemented in numrange_fluent.cpp.
  154. * Declared here so it can be friended.
  155. *
  156. * @internal
  157. */
  158. void touchRangeLocales(impl::RangeMacroProps& macros);
  159. } // namespace impl
  160. /**
  161. * Extra name reserved in case it is needed in the future.
  162. *
  163. * @stable ICU 63
  164. */
  165. typedef Notation CompactNotation;
  166. /**
  167. * Extra name reserved in case it is needed in the future.
  168. *
  169. * @stable ICU 63
  170. */
  171. typedef Notation SimpleNotation;
  172. /**
  173. * A class that defines the notation style to be used when formatting numbers in NumberFormatter.
  174. *
  175. * @stable ICU 60
  176. */
  177. class U_I18N_API Notation : public UMemory {
  178. public:
  179. /**
  180. * Print the number using scientific notation (also known as scientific form, standard index form, or standard form
  181. * in the UK). The format for scientific notation varies by locale; for example, many Western locales display the
  182. * number in the form "#E0", where the number is displayed with one digit before the decimal separator, zero or more
  183. * digits after the decimal separator, and the corresponding power of 10 displayed after the "E".
  184. *
  185. * <p>
  186. * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
  187. *
  188. * <pre>
  189. * 8.765E4
  190. * 8.765E3
  191. * 8.765E2
  192. * 8.765E1
  193. * 8.765E0
  194. * 8.765E-1
  195. * 8.765E-2
  196. * 8.765E-3
  197. * 0E0
  198. * </pre>
  199. *
  200. * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
  201. * @stable ICU 60
  202. */
  203. static ScientificNotation scientific();
  204. /**
  205. * Print the number using engineering notation, a variant of scientific notation in which the exponent must be
  206. * divisible by 3.
  207. *
  208. * <p>
  209. * Example outputs in <em>en-US</em> when printing 8.765E4 through 8.765E-3:
  210. *
  211. * <pre>
  212. * 87.65E3
  213. * 8.765E3
  214. * 876.5E0
  215. * 87.65E0
  216. * 8.765E0
  217. * 876.5E-3
  218. * 87.65E-3
  219. * 8.765E-3
  220. * 0E0
  221. * </pre>
  222. *
  223. * @return A ScientificNotation for chaining or passing to the NumberFormatter notation() setter.
  224. * @stable ICU 60
  225. */
  226. static ScientificNotation engineering();
  227. /**
  228. * Print the number using short-form compact notation.
  229. *
  230. * <p>
  231. * <em>Compact notation</em>, defined in Unicode Technical Standard #35 Part 3 Section 2.4.1, prints numbers with
  232. * localized prefixes or suffixes corresponding to different powers of ten. Compact notation is similar to
  233. * engineering notation in how it scales numbers.
  234. *
  235. * <p>
  236. * Compact notation is ideal for displaying large numbers (over ~1000) to humans while at the same time minimizing
  237. * screen real estate.
  238. *
  239. * <p>
  240. * In short form, the powers of ten are abbreviated. In <em>en-US</em>, the abbreviations are "K" for thousands, "M"
  241. * for millions, "B" for billions, and "T" for trillions. Example outputs in <em>en-US</em> when printing 8.765E7
  242. * through 8.765E0:
  243. *
  244. * <pre>
  245. * 88M
  246. * 8.8M
  247. * 876K
  248. * 88K
  249. * 8.8K
  250. * 876
  251. * 88
  252. * 8.8
  253. * </pre>
  254. *
  255. * <p>
  256. * When compact notation is specified without an explicit rounding precision, numbers are rounded off to the closest
  257. * integer after scaling the number by the corresponding power of 10, but with a digit shown after the decimal
  258. * separator if there is only one digit before the decimal separator. The default compact notation rounding precision
  259. * is equivalent to:
  260. *
  261. * <pre>
  262. * Precision::integer().withMinDigits(2)
  263. * </pre>
  264. *
  265. * @return A CompactNotation for passing to the NumberFormatter notation() setter.
  266. * @stable ICU 60
  267. */
  268. static CompactNotation compactShort();
  269. /**
  270. * Print the number using long-form compact notation. For more information on compact notation, see
  271. * {@link #compactShort}.
  272. *
  273. * <p>
  274. * In long form, the powers of ten are spelled out fully. Example outputs in <em>en-US</em> when printing 8.765E7
  275. * through 8.765E0:
  276. *
  277. * <pre>
  278. * 88 million
  279. * 8.8 million
  280. * 876 thousand
  281. * 88 thousand
  282. * 8.8 thousand
  283. * 876
  284. * 88
  285. * 8.8
  286. * </pre>
  287. *
  288. * @return A CompactNotation for passing to the NumberFormatter notation() setter.
  289. * @stable ICU 60
  290. */
  291. static CompactNotation compactLong();
  292. /**
  293. * Print the number using simple notation without any scaling by powers of ten. This is the default behavior.
  294. *
  295. * <p>
  296. * Since this is the default behavior, this method needs to be called only when it is necessary to override a
  297. * previous setting.
  298. *
  299. * <p>
  300. * Example outputs in <em>en-US</em> when printing 8.765E7 through 8.765E0:
  301. *
  302. * <pre>
  303. * 87,650,000
  304. * 8,765,000
  305. * 876,500
  306. * 87,650
  307. * 8,765
  308. * 876.5
  309. * 87.65
  310. * 8.765
  311. * </pre>
  312. *
  313. * @return A SimpleNotation for passing to the NumberFormatter notation() setter.
  314. * @stable ICU 60
  315. */
  316. static SimpleNotation simple();
  317. private:
  318. enum NotationType {
  319. NTN_SCIENTIFIC, NTN_COMPACT, NTN_SIMPLE, NTN_ERROR
  320. } fType;
  321. union NotationUnion {
  322. // For NTN_SCIENTIFIC
  323. /** @internal (private) */
  324. struct ScientificSettings {
  325. /** @internal (private) */
  326. int8_t fEngineeringInterval;
  327. /** @internal (private) */
  328. bool fRequireMinInt;
  329. /** @internal (private) */
  330. impl::digits_t fMinExponentDigits;
  331. /** @internal (private) */
  332. UNumberSignDisplay fExponentSignDisplay;
  333. } scientific;
  334. // For NTN_COMPACT
  335. UNumberCompactStyle compactStyle;
  336. // For NTN_ERROR
  337. UErrorCode errorCode;
  338. } fUnion;
  339. typedef NotationUnion::ScientificSettings ScientificSettings;
  340. Notation(const NotationType &type, const NotationUnion &union_) : fType(type), fUnion(union_) {}
  341. Notation(UErrorCode errorCode) : fType(NTN_ERROR) {
  342. fUnion.errorCode = errorCode;
  343. }
  344. Notation() : fType(NTN_SIMPLE), fUnion() {}
  345. UBool copyErrorTo(UErrorCode &status) const {
  346. if (fType == NTN_ERROR) {
  347. status = fUnion.errorCode;
  348. return true;
  349. }
  350. return false;
  351. }
  352. // To allow MacroProps to initialize empty instances:
  353. friend struct impl::MacroProps;
  354. friend class ScientificNotation;
  355. // To allow implementation to access internal types:
  356. friend class impl::NumberFormatterImpl;
  357. friend class impl::ScientificModifier;
  358. friend class impl::ScientificHandler;
  359. // To allow access to the skeleton generation code:
  360. friend class impl::GeneratorHelpers;
  361. };
  362. /**
  363. * A class that defines the scientific notation style to be used when formatting numbers in NumberFormatter.
  364. *
  365. * <p>
  366. * To create a ScientificNotation, use one of the factory methods in {@link Notation}.
  367. *
  368. * @stable ICU 60
  369. */
  370. class U_I18N_API ScientificNotation : public Notation {
  371. public:
  372. /**
  373. * Sets the minimum number of digits to show in the exponent of scientific notation, padding with zeros if
  374. * necessary. Useful for fixed-width display.
  375. *
  376. * <p>
  377. * For example, with minExponentDigits=2, the number 123 will be printed as "1.23E02" in <em>en-US</em> instead of
  378. * the default "1.23E2".
  379. *
  380. * @param minExponentDigits
  381. * The minimum number of digits to show in the exponent.
  382. * @return A ScientificNotation, for chaining.
  383. * @stable ICU 60
  384. */
  385. ScientificNotation withMinExponentDigits(int32_t minExponentDigits) const;
  386. /**
  387. * Sets whether to show the sign on positive and negative exponents in scientific notation. The default is AUTO,
  388. * showing the minus sign but not the plus sign.
  389. *
  390. * <p>
  391. * For example, with exponentSignDisplay=ALWAYS, the number 123 will be printed as "1.23E+2" in <em>en-US</em>
  392. * instead of the default "1.23E2".
  393. *
  394. * @param exponentSignDisplay
  395. * The strategy for displaying the sign in the exponent.
  396. * @return A ScientificNotation, for chaining.
  397. * @stable ICU 60
  398. */
  399. ScientificNotation withExponentSignDisplay(UNumberSignDisplay exponentSignDisplay) const;
  400. private:
  401. // Inherit constructor
  402. using Notation::Notation;
  403. // Raw constructor for NumberPropertyMapper
  404. ScientificNotation(int8_t fEngineeringInterval, bool fRequireMinInt, impl::digits_t fMinExponentDigits,
  405. UNumberSignDisplay fExponentSignDisplay);
  406. friend class Notation;
  407. // So that NumberPropertyMapper can create instances
  408. friend class impl::NumberPropertyMapper;
  409. };
  410. /**
  411. * Extra name reserved in case it is needed in the future.
  412. *
  413. * @stable ICU 63
  414. */
  415. typedef Precision SignificantDigitsPrecision;
  416. /**
  417. * A class that defines the rounding precision to be used when formatting numbers in NumberFormatter.
  418. *
  419. * <p>
  420. * To create a Precision, use one of the factory methods.
  421. *
  422. * @stable ICU 60
  423. */
  424. class U_I18N_API Precision : public UMemory {
  425. public:
  426. /**
  427. * Show all available digits to full precision.
  428. *
  429. * <p>
  430. * <strong>NOTE:</strong> When formatting a <em>double</em>, this method, along with {@link #minFraction} and
  431. * {@link #minSignificantDigits}, will trigger complex algorithm similar to <em>Dragon4</em> to determine the
  432. * low-order digits and the number of digits to display based on the value of the double.
  433. * If the number of fraction places or significant digits can be bounded, consider using {@link #maxFraction}
  434. * or {@link #maxSignificantDigits} instead to maximize performance.
  435. * For more information, read the following blog post.
  436. *
  437. * <p>
  438. * http://www.serpentine.com/blog/2011/06/29/here-be-dragons-advances-in-problems-you-didnt-even-know-you-had/
  439. *
  440. * @return A Precision for chaining or passing to the NumberFormatter precision() setter.
  441. * @stable ICU 60
  442. */
  443. static Precision unlimited();
  444. /**
  445. * Show numbers rounded if necessary to the nearest integer.
  446. *
  447. * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
  448. * @stable ICU 60
  449. */
  450. static FractionPrecision integer();
  451. /**
  452. * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
  453. * Additionally, pad with zeros to ensure that this number of places are always shown.
  454. *
  455. * <p>
  456. * Example output with minMaxFractionPlaces = 3:
  457. *
  458. * <p>
  459. * 87,650.000<br>
  460. * 8,765.000<br>
  461. * 876.500<br>
  462. * 87.650<br>
  463. * 8.765<br>
  464. * 0.876<br>
  465. * 0.088<br>
  466. * 0.009<br>
  467. * 0.000 (zero)
  468. *
  469. * <p>
  470. * This method is equivalent to {@link #minMaxFraction} with both arguments equal.
  471. *
  472. * @param minMaxFractionPlaces
  473. * The minimum and maximum number of numerals to display after the decimal separator (rounding if too
  474. * long or padding with zeros if too short).
  475. * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
  476. * @stable ICU 60
  477. */
  478. static FractionPrecision fixedFraction(int32_t minMaxFractionPlaces);
  479. /**
  480. * Always show at least a certain number of fraction places after the decimal separator, padding with zeros if
  481. * necessary. Do not perform rounding (display numbers to their full precision).
  482. *
  483. * <p>
  484. * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
  485. *
  486. * @param minFractionPlaces
  487. * The minimum number of numerals to display after the decimal separator (padding with zeros if
  488. * necessary).
  489. * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
  490. * @stable ICU 60
  491. */
  492. static FractionPrecision minFraction(int32_t minFractionPlaces);
  493. /**
  494. * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator).
  495. * Unlike the other fraction rounding strategies, this strategy does <em>not</em> pad zeros to the end of the
  496. * number.
  497. *
  498. * @param maxFractionPlaces
  499. * The maximum number of numerals to display after the decimal mark (rounding if necessary).
  500. * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
  501. * @stable ICU 60
  502. */
  503. static FractionPrecision maxFraction(int32_t maxFractionPlaces);
  504. /**
  505. * Show numbers rounded if necessary to a certain number of fraction places (numerals after the decimal separator);
  506. * in addition, always show at least a certain number of places after the decimal separator, padding with zeros if
  507. * necessary.
  508. *
  509. * @param minFractionPlaces
  510. * The minimum number of numerals to display after the decimal separator (padding with zeros if
  511. * necessary).
  512. * @param maxFractionPlaces
  513. * The maximum number of numerals to display after the decimal separator (rounding if necessary).
  514. * @return A FractionPrecision for chaining or passing to the NumberFormatter precision() setter.
  515. * @stable ICU 60
  516. */
  517. static FractionPrecision minMaxFraction(int32_t minFractionPlaces, int32_t maxFractionPlaces);
  518. /**
  519. * Show numbers rounded if necessary to a certain number of significant digits or significant figures. Additionally,
  520. * pad with zeros to ensure that this number of significant digits/figures are always shown.
  521. *
  522. * <p>
  523. * This method is equivalent to {@link #minMaxSignificantDigits} with both arguments equal.
  524. *
  525. * @param minMaxSignificantDigits
  526. * The minimum and maximum number of significant digits to display (rounding if too long or padding with
  527. * zeros if too short).
  528. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  529. * @stable ICU 62
  530. */
  531. static SignificantDigitsPrecision fixedSignificantDigits(int32_t minMaxSignificantDigits);
  532. /**
  533. * Always show at least a certain number of significant digits/figures, padding with zeros if necessary. Do not
  534. * perform rounding (display numbers to their full precision).
  535. *
  536. * <p>
  537. * <strong>NOTE:</strong> If you are formatting <em>doubles</em>, see the performance note in {@link #unlimited}.
  538. *
  539. * @param minSignificantDigits
  540. * The minimum number of significant digits to display (padding with zeros if too short).
  541. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  542. * @stable ICU 62
  543. */
  544. static SignificantDigitsPrecision minSignificantDigits(int32_t minSignificantDigits);
  545. /**
  546. * Show numbers rounded if necessary to a certain number of significant digits/figures.
  547. *
  548. * @param maxSignificantDigits
  549. * The maximum number of significant digits to display (rounding if too long).
  550. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  551. * @stable ICU 62
  552. */
  553. static SignificantDigitsPrecision maxSignificantDigits(int32_t maxSignificantDigits);
  554. /**
  555. * Show numbers rounded if necessary to a certain number of significant digits/figures; in addition, always show at
  556. * least a certain number of significant digits, padding with zeros if necessary.
  557. *
  558. * @param minSignificantDigits
  559. * The minimum number of significant digits to display (padding with zeros if necessary).
  560. * @param maxSignificantDigits
  561. * The maximum number of significant digits to display (rounding if necessary).
  562. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  563. * @stable ICU 62
  564. */
  565. static SignificantDigitsPrecision minMaxSignificantDigits(int32_t minSignificantDigits,
  566. int32_t maxSignificantDigits);
  567. /**
  568. * Show numbers rounded if necessary to the closest multiple of a certain rounding increment. For example, if the
  569. * rounding increment is 0.5, then round 1.2 to 1 and round 1.3 to 1.5.
  570. *
  571. * <p>
  572. * In order to ensure that numbers are padded to the appropriate number of fraction places, call
  573. * withMinFraction() on the return value of this method.
  574. * For example, to round to the nearest 0.5 and always display 2 numerals after the
  575. * decimal separator (to display 1.2 as "1.00" and 1.3 as "1.50"), you can run:
  576. *
  577. * <pre>
  578. * Precision::increment(0.5).withMinFraction(2)
  579. * </pre>
  580. *
  581. * @param roundingIncrement
  582. * The increment to which to round numbers.
  583. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  584. * @stable ICU 60
  585. */
  586. static IncrementPrecision increment(double roundingIncrement);
  587. /**
  588. * Version of `Precision::increment()` that takes an integer at a particular power of 10.
  589. *
  590. * To round to the nearest 0.5 and display 2 fraction digits, with this function, you should write one of the following:
  591. *
  592. * <pre>
  593. * Precision::incrementExact(5, -1).withMinFraction(2)
  594. * Precision::incrementExact(50, -2).withMinFraction(2)
  595. * Precision::incrementExact(50, -2)
  596. * </pre>
  597. *
  598. * This is analagous to ICU4J `Precision.increment(new BigDecimal("0.50"))`.
  599. *
  600. * This behavior is modeled after ECMA-402. For more information, see:
  601. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingincrement
  602. *
  603. * @param mantissa
  604. * The increment to which to round numbers.
  605. * @param magnitude
  606. * The power of 10 of the ones digit of the mantissa.
  607. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  608. * @stable ICU 71
  609. */
  610. static IncrementPrecision incrementExact(uint64_t mantissa, int16_t magnitude);
  611. /**
  612. * Show numbers rounded and padded according to the rules for the currency unit. The most common
  613. * rounding precision settings for currencies include <code>Precision::fixedFraction(2)</code>,
  614. * <code>Precision::integer()</code>, and <code>Precision::increment(0.05)</code> for cash transactions
  615. * ("nickel rounding").
  616. *
  617. * <p>
  618. * The exact rounding details will be resolved at runtime based on the currency unit specified in the
  619. * NumberFormatter chain. To round according to the rules for one currency while displaying the symbol for another
  620. * currency, the withCurrency() method can be called on the return value of this method.
  621. *
  622. * @param currencyUsage
  623. * Either STANDARD (for digital transactions) or CASH (for transactions where the rounding increment may
  624. * be limited by the available denominations of cash or coins).
  625. * @return A CurrencyPrecision for chaining or passing to the NumberFormatter precision() setter.
  626. * @stable ICU 60
  627. */
  628. static CurrencyPrecision currency(UCurrencyUsage currencyUsage);
  629. /**
  630. * Configure how trailing zeros are displayed on numbers. For example, to hide trailing zeros
  631. * when the number is an integer, use UNUM_TRAILING_ZERO_HIDE_IF_WHOLE.
  632. *
  633. * @param trailingZeroDisplay Option to configure the display of trailing zeros.
  634. * @stable ICU 69
  635. */
  636. Precision trailingZeroDisplay(UNumberTrailingZeroDisplay trailingZeroDisplay) const;
  637. private:
  638. enum PrecisionType {
  639. RND_BOGUS,
  640. RND_NONE,
  641. RND_FRACTION,
  642. RND_SIGNIFICANT,
  643. RND_FRACTION_SIGNIFICANT,
  644. // Used for strange increments like 3.14.
  645. RND_INCREMENT,
  646. // Used for increments with 1 as the only digit. This is different than fraction
  647. // rounding because it supports having additional trailing zeros. For example, this
  648. // class is used to round with the increment 0.010.
  649. RND_INCREMENT_ONE,
  650. // Used for increments with 5 as the only digit (nickel rounding).
  651. RND_INCREMENT_FIVE,
  652. RND_CURRENCY,
  653. RND_ERROR
  654. } fType;
  655. union PrecisionUnion {
  656. /** @internal (private) */
  657. struct FractionSignificantSettings {
  658. // For RND_FRACTION, RND_SIGNIFICANT, and RND_FRACTION_SIGNIFICANT
  659. /** @internal (private) */
  660. impl::digits_t fMinFrac;
  661. /** @internal (private) */
  662. impl::digits_t fMaxFrac;
  663. /** @internal (private) */
  664. impl::digits_t fMinSig;
  665. /** @internal (private) */
  666. impl::digits_t fMaxSig;
  667. /** @internal (private) */
  668. UNumberRoundingPriority fPriority;
  669. /**
  670. * Whether to retain trailing zeros based on the looser strategy.
  671. * @internal (private)
  672. */
  673. bool fRetain;
  674. } fracSig;
  675. /** @internal (private) */
  676. struct IncrementSettings {
  677. // For RND_INCREMENT, RND_INCREMENT_ONE, and RND_INCREMENT_FIVE
  678. // Note: This is a union, so we shouldn't own memory, since
  679. // the default destructor would leak it.
  680. /** @internal (private) */
  681. uint64_t fIncrement;
  682. /** @internal (private) */
  683. impl::digits_t fIncrementMagnitude;
  684. /** @internal (private) */
  685. impl::digits_t fMinFrac;
  686. } increment;
  687. UCurrencyUsage currencyUsage; // For RND_CURRENCY
  688. UErrorCode errorCode; // For RND_ERROR
  689. } fUnion;
  690. UNumberTrailingZeroDisplay fTrailingZeroDisplay = UNUM_TRAILING_ZERO_AUTO;
  691. typedef PrecisionUnion::FractionSignificantSettings FractionSignificantSettings;
  692. typedef PrecisionUnion::IncrementSettings IncrementSettings;
  693. Precision(const PrecisionType& type, const PrecisionUnion& union_)
  694. : fType(type), fUnion(union_) {}
  695. Precision(UErrorCode errorCode) : fType(RND_ERROR) {
  696. fUnion.errorCode = errorCode;
  697. }
  698. Precision() : fType(RND_BOGUS) {}
  699. bool isBogus() const {
  700. return fType == RND_BOGUS;
  701. }
  702. UBool copyErrorTo(UErrorCode &status) const {
  703. if (fType == RND_ERROR) {
  704. status = fUnion.errorCode;
  705. return true;
  706. }
  707. return false;
  708. }
  709. // On the parent type so that this method can be called internally on Precision instances.
  710. Precision withCurrency(const CurrencyUnit &currency, UErrorCode &status) const;
  711. static FractionPrecision constructFraction(int32_t minFrac, int32_t maxFrac);
  712. static Precision constructSignificant(int32_t minSig, int32_t maxSig);
  713. static Precision constructFractionSignificant(
  714. const FractionPrecision &base,
  715. int32_t minSig,
  716. int32_t maxSig,
  717. UNumberRoundingPriority priority,
  718. bool retain);
  719. static IncrementPrecision constructIncrement(uint64_t increment, impl::digits_t magnitude);
  720. static CurrencyPrecision constructCurrency(UCurrencyUsage usage);
  721. // To allow MacroProps/MicroProps to initialize bogus instances:
  722. friend struct impl::MacroProps;
  723. friend struct impl::MicroProps;
  724. // To allow NumberFormatterImpl to access isBogus() and other internal methods:
  725. friend class impl::NumberFormatterImpl;
  726. // To allow NumberPropertyMapper to create instances from DecimalFormatProperties:
  727. friend class impl::NumberPropertyMapper;
  728. // To allow access to the main implementation class:
  729. friend class impl::RoundingImpl;
  730. // To allow child classes to call private methods:
  731. friend class FractionPrecision;
  732. friend class CurrencyPrecision;
  733. friend class IncrementPrecision;
  734. // To allow access to the skeleton generation code:
  735. friend class impl::GeneratorHelpers;
  736. // To allow access to isBogus and the default (bogus) constructor:
  737. friend class units::UnitsRouter;
  738. };
  739. /**
  740. * A class that defines a rounding precision based on a number of fraction places and optionally significant digits to be
  741. * used when formatting numbers in NumberFormatter.
  742. *
  743. * <p>
  744. * To create a FractionPrecision, use one of the factory methods on Precision.
  745. *
  746. * @stable ICU 60
  747. */
  748. class U_I18N_API FractionPrecision : public Precision {
  749. public:
  750. /**
  751. * Override maximum fraction digits with maximum significant digits depending on the magnitude
  752. * of the number. See UNumberRoundingPriority.
  753. *
  754. * @param minSignificantDigits
  755. * Pad trailing zeros to achieve this minimum number of significant digits.
  756. * @param maxSignificantDigits
  757. * Round the number to achieve this maximum number of significant digits.
  758. * @param priority
  759. * How to disambiguate between fraction digits and significant digits.
  760. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  761. *
  762. * @stable ICU 69
  763. */
  764. Precision withSignificantDigits(
  765. int32_t minSignificantDigits,
  766. int32_t maxSignificantDigits,
  767. UNumberRoundingPriority priority) const;
  768. /**
  769. * Ensure that no less than this number of significant digits are retained when rounding
  770. * according to fraction rules.
  771. *
  772. * For example, with integer rounding, the number 3.141 becomes "3". However, with minimum
  773. * figures set to 2, 3.141 becomes "3.1" instead.
  774. *
  775. * This setting does not affect the number of trailing zeros. For example, 3.01 would print as
  776. * "3", not "3.0".
  777. *
  778. * This is equivalent to `withSignificantDigits(1, minSignificantDigits, RELAXED)`.
  779. *
  780. * @param minSignificantDigits
  781. * The number of significant figures to guarantee.
  782. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  783. * @stable ICU 60
  784. */
  785. Precision withMinDigits(int32_t minSignificantDigits) const;
  786. /**
  787. * Ensure that no more than this number of significant digits are retained when rounding
  788. * according to fraction rules.
  789. *
  790. * For example, with integer rounding, the number 123.4 becomes "123". However, with maximum
  791. * figures set to 2, 123.4 becomes "120" instead.
  792. *
  793. * This setting does not affect the number of trailing zeros. For example, with fixed fraction
  794. * of 2, 123.4 would become "120.00".
  795. *
  796. * This is equivalent to `withSignificantDigits(1, maxSignificantDigits, STRICT)`.
  797. *
  798. * @param maxSignificantDigits
  799. * Round the number to no more than this number of significant figures.
  800. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  801. * @stable ICU 60
  802. */
  803. Precision withMaxDigits(int32_t maxSignificantDigits) const;
  804. private:
  805. // Inherit constructor
  806. using Precision::Precision;
  807. // To allow parent class to call this class's constructor:
  808. friend class Precision;
  809. };
  810. /**
  811. * A class that defines a rounding precision parameterized by a currency to be used when formatting numbers in
  812. * NumberFormatter.
  813. *
  814. * <p>
  815. * To create a CurrencyPrecision, use one of the factory methods on Precision.
  816. *
  817. * @stable ICU 60
  818. */
  819. class U_I18N_API CurrencyPrecision : public Precision {
  820. public:
  821. /**
  822. * Associates a currency with this rounding precision.
  823. *
  824. * <p>
  825. * <strong>Calling this method is <em>not required</em></strong>, because the currency specified in unit()
  826. * is automatically applied to currency rounding precisions. However,
  827. * this method enables you to override that automatic association.
  828. *
  829. * <p>
  830. * This method also enables numbers to be formatted using currency rounding rules without explicitly using a
  831. * currency format.
  832. *
  833. * @param currency
  834. * The currency to associate with this rounding precision.
  835. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  836. * @stable ICU 60
  837. */
  838. Precision withCurrency(const CurrencyUnit &currency) const;
  839. private:
  840. // Inherit constructor
  841. using Precision::Precision;
  842. // To allow parent class to call this class's constructor:
  843. friend class Precision;
  844. };
  845. /**
  846. * A class that defines a rounding precision parameterized by a rounding increment to be used when formatting numbers in
  847. * NumberFormatter.
  848. *
  849. * <p>
  850. * To create an IncrementPrecision, use one of the factory methods on Precision.
  851. *
  852. * @stable ICU 60
  853. */
  854. class U_I18N_API IncrementPrecision : public Precision {
  855. public:
  856. /**
  857. * Specifies the minimum number of fraction digits to render after the decimal separator, padding with zeros if
  858. * necessary. By default, no trailing zeros are added.
  859. *
  860. * <p>
  861. * For example, if the rounding increment is 0.5 and minFrac is 2, then the resulting strings include "0.00",
  862. * "0.50", "1.00", and "1.50".
  863. *
  864. * <p>
  865. * Note: In ICU4J, this functionality is accomplished via the scale of the BigDecimal rounding increment.
  866. *
  867. * @param minFrac The minimum number of digits after the decimal separator.
  868. * @return A precision for chaining or passing to the NumberFormatter precision() setter.
  869. * @stable ICU 60
  870. */
  871. Precision withMinFraction(int32_t minFrac) const;
  872. private:
  873. // Inherit constructor
  874. using Precision::Precision;
  875. // To allow parent class to call this class's constructor:
  876. friend class Precision;
  877. };
  878. /**
  879. * A class that defines the strategy for padding and truncating integers before the decimal separator.
  880. *
  881. * <p>
  882. * To create an IntegerWidth, use one of the factory methods.
  883. *
  884. * @stable ICU 60
  885. * @see NumberFormatter
  886. */
  887. class U_I18N_API IntegerWidth : public UMemory {
  888. public:
  889. /**
  890. * Pad numbers at the beginning with zeros to guarantee a certain number of numerals before the decimal separator.
  891. *
  892. * <p>
  893. * For example, with minInt=3, the number 55 will get printed as "055".
  894. *
  895. * @param minInt
  896. * The minimum number of places before the decimal separator.
  897. * @return An IntegerWidth for chaining or passing to the NumberFormatter integerWidth() setter.
  898. * @stable ICU 60
  899. */
  900. static IntegerWidth zeroFillTo(int32_t minInt);
  901. /**
  902. * Truncate numbers exceeding a certain number of numerals before the decimal separator.
  903. *
  904. * For example, with maxInt=3, the number 1234 will get printed as "234".
  905. *
  906. * @param maxInt
  907. * The maximum number of places before the decimal separator. maxInt == -1 means no
  908. * truncation.
  909. * @return An IntegerWidth for passing to the NumberFormatter integerWidth() setter.
  910. * @stable ICU 60
  911. */
  912. IntegerWidth truncateAt(int32_t maxInt);
  913. private:
  914. union {
  915. struct {
  916. impl::digits_t fMinInt;
  917. impl::digits_t fMaxInt;
  918. bool fFormatFailIfMoreThanMaxDigits;
  919. } minMaxInt;
  920. UErrorCode errorCode;
  921. } fUnion;
  922. bool fHasError = false;
  923. IntegerWidth(impl::digits_t minInt, impl::digits_t maxInt, bool formatFailIfMoreThanMaxDigits);
  924. IntegerWidth(UErrorCode errorCode) { // NOLINT
  925. fUnion.errorCode = errorCode;
  926. fHasError = true;
  927. }
  928. IntegerWidth() { // NOLINT
  929. fUnion.minMaxInt.fMinInt = -1;
  930. }
  931. /** Returns the default instance. */
  932. static IntegerWidth standard() {
  933. return IntegerWidth::zeroFillTo(1);
  934. }
  935. bool isBogus() const {
  936. return !fHasError && fUnion.minMaxInt.fMinInt == -1;
  937. }
  938. UBool copyErrorTo(UErrorCode &status) const {
  939. if (fHasError) {
  940. status = fUnion.errorCode;
  941. return true;
  942. }
  943. return false;
  944. }
  945. void apply(impl::DecimalQuantity &quantity, UErrorCode &status) const;
  946. bool operator==(const IntegerWidth& other) const;
  947. // To allow MacroProps/MicroProps to initialize empty instances:
  948. friend struct impl::MacroProps;
  949. friend struct impl::MicroProps;
  950. // To allow NumberFormatterImpl to access isBogus():
  951. friend class impl::NumberFormatterImpl;
  952. // To allow the use of this class when formatting:
  953. friend class impl::MutablePatternModifier;
  954. friend class impl::ImmutablePatternModifier;
  955. // So that NumberPropertyMapper can create instances
  956. friend class impl::NumberPropertyMapper;
  957. // To allow access to the skeleton generation code:
  958. friend class impl::GeneratorHelpers;
  959. };
  960. /**
  961. * A class that defines a quantity by which a number should be multiplied when formatting.
  962. *
  963. * <p>
  964. * To create a Scale, use one of the factory methods.
  965. *
  966. * @stable ICU 62
  967. */
  968. class U_I18N_API Scale : public UMemory {
  969. public:
  970. /**
  971. * Do not change the value of numbers when formatting or parsing.
  972. *
  973. * @return A Scale to prevent any multiplication.
  974. * @stable ICU 62
  975. */
  976. static Scale none();
  977. /**
  978. * Multiply numbers by a power of ten before formatting. Useful for combining with a percent unit:
  979. *
  980. * <pre>
  981. * NumberFormatter::with().unit(NoUnit::percent()).multiplier(Scale::powerOfTen(2))
  982. * </pre>
  983. *
  984. * @return A Scale for passing to the setter in NumberFormatter.
  985. * @stable ICU 62
  986. */
  987. static Scale powerOfTen(int32_t power);
  988. /**
  989. * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
  990. *
  991. * This method takes a string in a decimal number format with syntax
  992. * as defined in the Decimal Arithmetic Specification, available at
  993. * http://speleotrove.com/decimal
  994. *
  995. * Also see the version of this method that takes a double.
  996. *
  997. * @return A Scale for passing to the setter in NumberFormatter.
  998. * @stable ICU 62
  999. */
  1000. static Scale byDecimal(StringPiece multiplicand);
  1001. /**
  1002. * Multiply numbers by an arbitrary value before formatting. Useful for unit conversions.
  1003. *
  1004. * This method takes a double; also see the version of this method that takes an exact decimal.
  1005. *
  1006. * @return A Scale for passing to the setter in NumberFormatter.
  1007. * @stable ICU 62
  1008. */
  1009. static Scale byDouble(double multiplicand);
  1010. /**
  1011. * Multiply a number by both a power of ten and by an arbitrary double value.
  1012. *
  1013. * @return A Scale for passing to the setter in NumberFormatter.
  1014. * @stable ICU 62
  1015. */
  1016. static Scale byDoubleAndPowerOfTen(double multiplicand, int32_t power);
  1017. // We need a custom destructor for the DecNum, which means we need to declare
  1018. // the copy/move constructor/assignment quartet.
  1019. /** @stable ICU 62 */
  1020. Scale(const Scale& other);
  1021. /** @stable ICU 62 */
  1022. Scale& operator=(const Scale& other);
  1023. /** @stable ICU 62 */
  1024. Scale(Scale&& src) noexcept;
  1025. /** @stable ICU 62 */
  1026. Scale& operator=(Scale&& src) noexcept;
  1027. /** @stable ICU 62 */
  1028. ~Scale();
  1029. #ifndef U_HIDE_INTERNAL_API
  1030. /** @internal */
  1031. Scale(int32_t magnitude, impl::DecNum* arbitraryToAdopt);
  1032. #endif /* U_HIDE_INTERNAL_API */
  1033. private:
  1034. int32_t fMagnitude;
  1035. impl::DecNum* fArbitrary;
  1036. UErrorCode fError;
  1037. Scale(UErrorCode error) : fMagnitude(0), fArbitrary(nullptr), fError(error) {}
  1038. Scale() : fMagnitude(0), fArbitrary(nullptr), fError(U_ZERO_ERROR) {}
  1039. bool isValid() const {
  1040. return fMagnitude != 0 || fArbitrary != nullptr;
  1041. }
  1042. UBool copyErrorTo(UErrorCode &status) const {
  1043. if (U_FAILURE(fError)) {
  1044. status = fError;
  1045. return true;
  1046. }
  1047. return false;
  1048. }
  1049. void applyTo(impl::DecimalQuantity& quantity) const;
  1050. void applyReciprocalTo(impl::DecimalQuantity& quantity) const;
  1051. // To allow MacroProps/MicroProps to initialize empty instances:
  1052. friend struct impl::MacroProps;
  1053. friend struct impl::MicroProps;
  1054. // To allow NumberFormatterImpl to access isBogus() and perform other operations:
  1055. friend class impl::NumberFormatterImpl;
  1056. // To allow the helper class MultiplierFormatHandler access to private fields:
  1057. friend class impl::MultiplierFormatHandler;
  1058. // To allow access to the skeleton generation code:
  1059. friend class impl::GeneratorHelpers;
  1060. // To allow access to parsing code:
  1061. friend class ::icu::numparse::impl::NumberParserImpl;
  1062. friend class ::icu::numparse::impl::MultiplierParseHandler;
  1063. };
  1064. namespace impl {
  1065. // Do not enclose entire StringProp with #ifndef U_HIDE_INTERNAL_API, needed for a protected field.
  1066. // And do not enclose its class boilerplate within #ifndef U_HIDE_INTERNAL_API.
  1067. /**
  1068. * Manages NumberFormatterSettings::usage()'s char* instance on the heap.
  1069. * @internal
  1070. */
  1071. class U_I18N_API StringProp : public UMemory {
  1072. public:
  1073. /** @internal */
  1074. ~StringProp();
  1075. /** @internal */
  1076. StringProp(const StringProp &other);
  1077. /** @internal */
  1078. StringProp &operator=(const StringProp &other);
  1079. #ifndef U_HIDE_INTERNAL_API
  1080. /** @internal */
  1081. StringProp(StringProp &&src) noexcept;
  1082. /** @internal */
  1083. StringProp &operator=(StringProp &&src) noexcept;
  1084. /** @internal */
  1085. int16_t length() const {
  1086. return fLength;
  1087. }
  1088. /** @internal
  1089. * Makes a copy of value. Set to "" to unset.
  1090. */
  1091. void set(StringPiece value);
  1092. /** @internal */
  1093. bool isSet() const {
  1094. return fLength > 0;
  1095. }
  1096. #endif // U_HIDE_INTERNAL_API
  1097. private:
  1098. char *fValue;
  1099. int16_t fLength;
  1100. UErrorCode fError;
  1101. StringProp() : fValue(nullptr), fLength(0), fError(U_ZERO_ERROR) {
  1102. }
  1103. /** @internal (private) */
  1104. UBool copyErrorTo(UErrorCode &status) const {
  1105. if (U_FAILURE(fError)) {
  1106. status = fError;
  1107. return true;
  1108. }
  1109. return false;
  1110. }
  1111. // Allow NumberFormatterImpl to access fValue.
  1112. friend class impl::NumberFormatterImpl;
  1113. // Allow skeleton generation code to access private members.
  1114. friend class impl::GeneratorHelpers;
  1115. // Allow MacroProps/MicroProps to initialize empty instances and to call
  1116. // copyErrorTo().
  1117. friend struct impl::MacroProps;
  1118. };
  1119. // Do not enclose entire SymbolsWrapper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
  1120. /** @internal */
  1121. class U_I18N_API SymbolsWrapper : public UMemory {
  1122. public:
  1123. /** @internal */
  1124. SymbolsWrapper() : fType(SYMPTR_NONE), fPtr{nullptr} {}
  1125. /** @internal */
  1126. SymbolsWrapper(const SymbolsWrapper &other);
  1127. /** @internal */
  1128. SymbolsWrapper &operator=(const SymbolsWrapper &other);
  1129. /** @internal */
  1130. SymbolsWrapper(SymbolsWrapper&& src) noexcept;
  1131. /** @internal */
  1132. SymbolsWrapper &operator=(SymbolsWrapper&& src) noexcept;
  1133. /** @internal */
  1134. ~SymbolsWrapper();
  1135. #ifndef U_HIDE_INTERNAL_API
  1136. /**
  1137. * The provided object is copied, but we do not adopt it.
  1138. * @internal
  1139. */
  1140. void setTo(const DecimalFormatSymbols &dfs);
  1141. /**
  1142. * Adopt the provided object.
  1143. * @internal
  1144. */
  1145. void setTo(const NumberingSystem *ns);
  1146. /**
  1147. * Whether the object is currently holding a DecimalFormatSymbols.
  1148. * @internal
  1149. */
  1150. bool isDecimalFormatSymbols() const;
  1151. /**
  1152. * Whether the object is currently holding a NumberingSystem.
  1153. * @internal
  1154. */
  1155. bool isNumberingSystem() const;
  1156. /**
  1157. * Get the DecimalFormatSymbols pointer. No ownership change.
  1158. * @internal
  1159. */
  1160. const DecimalFormatSymbols *getDecimalFormatSymbols() const;
  1161. /**
  1162. * Get the NumberingSystem pointer. No ownership change.
  1163. * @internal
  1164. */
  1165. const NumberingSystem *getNumberingSystem() const;
  1166. #endif // U_HIDE_INTERNAL_API
  1167. /** @internal */
  1168. UBool copyErrorTo(UErrorCode &status) const {
  1169. if (fType == SYMPTR_DFS && fPtr.dfs == nullptr) {
  1170. status = U_MEMORY_ALLOCATION_ERROR;
  1171. return true;
  1172. } else if (fType == SYMPTR_NS && fPtr.ns == nullptr) {
  1173. status = U_MEMORY_ALLOCATION_ERROR;
  1174. return true;
  1175. }
  1176. return false;
  1177. }
  1178. private:
  1179. enum SymbolsPointerType {
  1180. SYMPTR_NONE, SYMPTR_DFS, SYMPTR_NS
  1181. } fType;
  1182. union {
  1183. const DecimalFormatSymbols *dfs;
  1184. const NumberingSystem *ns;
  1185. } fPtr;
  1186. void doCopyFrom(const SymbolsWrapper &other);
  1187. void doMoveFrom(SymbolsWrapper&& src);
  1188. void doCleanup();
  1189. };
  1190. // Do not enclose entire Grouper with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
  1191. /** @internal */
  1192. class U_I18N_API Grouper : public UMemory {
  1193. public:
  1194. #ifndef U_HIDE_INTERNAL_API
  1195. /** @internal */
  1196. static Grouper forStrategy(UNumberGroupingStrategy grouping);
  1197. /**
  1198. * Resolve the values in Properties to a Grouper object.
  1199. * @internal
  1200. */
  1201. static Grouper forProperties(const DecimalFormatProperties& properties);
  1202. // Future: static Grouper forProperties(DecimalFormatProperties& properties);
  1203. /** @internal */
  1204. Grouper(int16_t grouping1, int16_t grouping2, int16_t minGrouping, UNumberGroupingStrategy strategy)
  1205. : fGrouping1(grouping1),
  1206. fGrouping2(grouping2),
  1207. fMinGrouping(minGrouping),
  1208. fStrategy(strategy) {}
  1209. /** @internal */
  1210. int16_t getPrimary() const;
  1211. /** @internal */
  1212. int16_t getSecondary() const;
  1213. #endif // U_HIDE_INTERNAL_API
  1214. private:
  1215. /**
  1216. * The grouping sizes, with the following special values:
  1217. * <ul>
  1218. * <li>-1 = no grouping
  1219. * <li>-2 = needs locale data
  1220. * <li>-4 = fall back to Western grouping if not in locale
  1221. * </ul>
  1222. */
  1223. int16_t fGrouping1;
  1224. int16_t fGrouping2;
  1225. /**
  1226. * The minimum grouping size, with the following special values:
  1227. * <ul>
  1228. * <li>-2 = needs locale data
  1229. * <li>-3 = no less than 2
  1230. * </ul>
  1231. */
  1232. int16_t fMinGrouping;
  1233. /**
  1234. * The UNumberGroupingStrategy that was used to create this Grouper, or UNUM_GROUPING_COUNT if this
  1235. * was not created from a UNumberGroupingStrategy.
  1236. */
  1237. UNumberGroupingStrategy fStrategy;
  1238. Grouper() : fGrouping1(-3) {}
  1239. bool isBogus() const {
  1240. return fGrouping1 == -3;
  1241. }
  1242. /** NON-CONST: mutates the current instance. */
  1243. void setLocaleData(const impl::ParsedPatternInfo &patternInfo, const Locale& locale);
  1244. bool groupAtPosition(int32_t position, const impl::DecimalQuantity &value) const;
  1245. // To allow MacroProps/MicroProps to initialize empty instances:
  1246. friend struct MacroProps;
  1247. friend struct MicroProps;
  1248. friend struct SimpleMicroProps;
  1249. // To allow NumberFormatterImpl to access isBogus() and perform other operations:
  1250. friend class NumberFormatterImpl;
  1251. friend class ::icu::number::SimpleNumberFormatter;
  1252. // To allow NumberParserImpl to perform setLocaleData():
  1253. friend class ::icu::numparse::impl::NumberParserImpl;
  1254. // To allow access to the skeleton generation code:
  1255. friend class impl::GeneratorHelpers;
  1256. };
  1257. // Do not enclose entire Padder with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
  1258. /** @internal */
  1259. class U_I18N_API Padder : public UMemory {
  1260. public:
  1261. #ifndef U_HIDE_INTERNAL_API
  1262. /** @internal */
  1263. static Padder none();
  1264. /** @internal */
  1265. static Padder codePoints(UChar32 cp, int32_t targetWidth, UNumberFormatPadPosition position);
  1266. /** @internal */
  1267. static Padder forProperties(const DecimalFormatProperties& properties);
  1268. #endif // U_HIDE_INTERNAL_API
  1269. private:
  1270. UChar32 fWidth; // -3 = error; -2 = bogus; -1 = no padding
  1271. union {
  1272. struct {
  1273. int32_t fCp;
  1274. UNumberFormatPadPosition fPosition;
  1275. } padding;
  1276. UErrorCode errorCode;
  1277. } fUnion;
  1278. Padder(UChar32 cp, int32_t width, UNumberFormatPadPosition position);
  1279. Padder(int32_t width);
  1280. Padder(UErrorCode errorCode) : fWidth(-3) { // NOLINT
  1281. fUnion.errorCode = errorCode;
  1282. }
  1283. Padder() : fWidth(-2) {} // NOLINT
  1284. bool isBogus() const {
  1285. return fWidth == -2;
  1286. }
  1287. UBool copyErrorTo(UErrorCode &status) const {
  1288. if (fWidth == -3) {
  1289. status = fUnion.errorCode;
  1290. return true;
  1291. }
  1292. return false;
  1293. }
  1294. bool isValid() const {
  1295. return fWidth > 0;
  1296. }
  1297. int32_t padAndApply(const impl::Modifier &mod1, const impl::Modifier &mod2,
  1298. FormattedStringBuilder &string, int32_t leftIndex, int32_t rightIndex,
  1299. UErrorCode &status) const;
  1300. // To allow MacroProps/MicroProps to initialize empty instances:
  1301. friend struct MacroProps;
  1302. friend struct MicroProps;
  1303. // To allow NumberFormatterImpl to access isBogus() and perform other operations:
  1304. friend class impl::NumberFormatterImpl;
  1305. // To allow access to the skeleton generation code:
  1306. friend class impl::GeneratorHelpers;
  1307. };
  1308. // Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
  1309. /** @internal */
  1310. struct U_I18N_API MacroProps : public UMemory {
  1311. /** @internal */
  1312. Notation notation;
  1313. /** @internal */
  1314. MeasureUnit unit; // = MeasureUnit(); (the base dimensionless unit)
  1315. /** @internal */
  1316. MeasureUnit perUnit; // = MeasureUnit(); (the base dimensionless unit)
  1317. /** @internal */
  1318. Precision precision; // = Precision(); (bogus)
  1319. /** @internal */
  1320. UNumberFormatRoundingMode roundingMode = UNUM_ROUND_HALFEVEN;
  1321. /** @internal */
  1322. Grouper grouper; // = Grouper(); (bogus)
  1323. /** @internal */
  1324. Padder padder; // = Padder(); (bogus)
  1325. /** @internal */
  1326. IntegerWidth integerWidth; // = IntegerWidth(); (bogus)
  1327. /** @internal */
  1328. SymbolsWrapper symbols;
  1329. // UNUM_XYZ_COUNT denotes null (bogus) values.
  1330. /** @internal */
  1331. UNumberUnitWidth unitWidth = UNUM_UNIT_WIDTH_COUNT;
  1332. /** @internal */
  1333. UNumberSignDisplay sign = UNUM_SIGN_COUNT;
  1334. /** @internal */
  1335. bool approximately = false;
  1336. /** @internal */
  1337. UNumberDecimalSeparatorDisplay decimal = UNUM_DECIMAL_SEPARATOR_COUNT;
  1338. /** @internal */
  1339. Scale scale; // = Scale(); (benign value)
  1340. /** @internal */
  1341. StringProp usage; // = StringProp(); (no usage)
  1342. /** @internal */
  1343. StringProp unitDisplayCase; // = StringProp(); (nominative)
  1344. /** @internal */
  1345. const AffixPatternProvider* affixProvider = nullptr; // no ownership
  1346. /** @internal */
  1347. const PluralRules* rules = nullptr; // no ownership
  1348. /** @internal */
  1349. int32_t threshold = kInternalDefaultThreshold;
  1350. /** @internal */
  1351. Locale locale;
  1352. // NOTE: Uses default copy and move constructors.
  1353. /**
  1354. * Check all members for errors.
  1355. * @internal
  1356. */
  1357. bool copyErrorTo(UErrorCode &status) const {
  1358. return notation.copyErrorTo(status) || precision.copyErrorTo(status) ||
  1359. padder.copyErrorTo(status) || integerWidth.copyErrorTo(status) ||
  1360. symbols.copyErrorTo(status) || scale.copyErrorTo(status) || usage.copyErrorTo(status) ||
  1361. unitDisplayCase.copyErrorTo(status);
  1362. }
  1363. };
  1364. } // namespace impl
  1365. #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
  1366. // Ignore MSVC warning 4661. This is generated for NumberFormatterSettings<>::toSkeleton() as this method
  1367. // is defined elsewhere (in number_skeletons.cpp). The compiler is warning that the explicit template instantiation
  1368. // inside this single translation unit (CPP file) is incomplete, and thus it isn't sure if the template class is
  1369. // fully defined. However, since each translation unit explicitly instantiates all the necessary template classes,
  1370. // they will all be passed to the linker, and the linker will still find and export all the class members.
  1371. #pragma warning(push)
  1372. #pragma warning(disable: 4661)
  1373. #endif
  1374. /**
  1375. * An abstract base class for specifying settings related to number formatting. This class is implemented by
  1376. * {@link UnlocalizedNumberFormatter} and {@link LocalizedNumberFormatter}. This class is not intended for
  1377. * public subclassing.
  1378. */
  1379. template<typename Derived>
  1380. class U_I18N_API NumberFormatterSettings {
  1381. public:
  1382. /**
  1383. * Specifies the notation style (simple, scientific, or compact) for rendering numbers.
  1384. *
  1385. * <ul>
  1386. * <li>Simple notation: "12,300"
  1387. * <li>Scientific notation: "1.23E4"
  1388. * <li>Compact notation: "12K"
  1389. * </ul>
  1390. *
  1391. * <p>
  1392. * All notation styles will be properly localized with locale data, and all notation styles are compatible with
  1393. * units, rounding precisions, and other number formatter settings.
  1394. *
  1395. * <p>
  1396. * Pass this method the return value of a {@link Notation} factory method. For example:
  1397. *
  1398. * <pre>
  1399. * NumberFormatter::with().notation(Notation::compactShort())
  1400. * </pre>
  1401. *
  1402. * The default is to use simple notation.
  1403. *
  1404. * @param notation
  1405. * The notation strategy to use.
  1406. * @return The fluent chain.
  1407. * @see Notation
  1408. * @stable ICU 60
  1409. */
  1410. Derived notation(const Notation &notation) const &;
  1411. /**
  1412. * Overload of notation() for use on an rvalue reference.
  1413. *
  1414. * @param notation
  1415. * The notation strategy to use.
  1416. * @return The fluent chain.
  1417. * @see #notation
  1418. * @stable ICU 62
  1419. */
  1420. Derived notation(const Notation &notation) &&;
  1421. /**
  1422. * Specifies the unit (unit of measure, currency, or percent) to associate with rendered numbers.
  1423. *
  1424. * <ul>
  1425. * <li>Unit of measure: "12.3 meters"
  1426. * <li>Currency: "$12.30"
  1427. * <li>Percent: "12.3%"
  1428. * </ul>
  1429. *
  1430. * All units will be properly localized with locale data, and all units are compatible with notation styles,
  1431. * rounding precisions, and other number formatter settings.
  1432. *
  1433. * \note If the usage() is set, the output unit **will be changed** to
  1434. * produce localised units, according to usage, locale and unit. See
  1435. * FormattedNumber::getOutputUnit().
  1436. *
  1437. * Pass this method any instance of {@link MeasureUnit}. For units of measure:
  1438. *
  1439. * <pre>
  1440. * NumberFormatter::with().unit(MeasureUnit::getMeter())
  1441. * NumberFormatter::with().unit(MeasureUnit::forIdentifier("foot-per-second", status))
  1442. * </pre>
  1443. *
  1444. * Currency:
  1445. *
  1446. * <pre>
  1447. * NumberFormatter::with().unit(CurrencyUnit(u"USD", status))
  1448. * </pre>
  1449. *
  1450. * Percent:
  1451. *
  1452. * <pre>
  1453. * NumberFormatter::with().unit(NoUnit.percent())
  1454. * </pre>
  1455. *
  1456. * See {@link #perUnit} for information on how to format strings like "5 meters per second".
  1457. *
  1458. * The default is to render without units (equivalent to NoUnit.base()).
  1459. *
  1460. * @param unit
  1461. * The unit to render.
  1462. * @return The fluent chain.
  1463. * @see MeasureUnit
  1464. * @see Currency
  1465. * @see NoUnit
  1466. * @see #perUnit
  1467. * @stable ICU 60
  1468. */
  1469. Derived unit(const icu::MeasureUnit &unit) const &;
  1470. /**
  1471. * Overload of unit() for use on an rvalue reference.
  1472. *
  1473. * @param unit
  1474. * The unit to render.
  1475. * @return The fluent chain.
  1476. * @see #unit
  1477. * @stable ICU 62
  1478. */
  1479. Derived unit(const icu::MeasureUnit &unit) &&;
  1480. /**
  1481. * Like unit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
  1482. * methods that return pointers that need ownership.
  1483. *
  1484. * Note: consider using the MeasureFormat factory methods that return by value.
  1485. *
  1486. * @param unit
  1487. * The unit to render.
  1488. * @return The fluent chain.
  1489. * @see #unit
  1490. * @see MeasureUnit
  1491. * @stable ICU 60
  1492. */
  1493. Derived adoptUnit(icu::MeasureUnit *unit) const &;
  1494. /**
  1495. * Overload of adoptUnit() for use on an rvalue reference.
  1496. *
  1497. * @param unit
  1498. * The unit to render.
  1499. * @return The fluent chain.
  1500. * @see #adoptUnit
  1501. * @stable ICU 62
  1502. */
  1503. Derived adoptUnit(icu::MeasureUnit *unit) &&;
  1504. /**
  1505. * Sets a unit to be used in the denominator. For example, to format "3 m/s", pass METER to the unit and SECOND to
  1506. * the perUnit.
  1507. *
  1508. * Pass this method any instance of {@link MeasureUnit}. Example:
  1509. *
  1510. * <pre>
  1511. * NumberFormatter::with()
  1512. * .unit(MeasureUnit::getMeter())
  1513. * .perUnit(MeasureUnit::getSecond())
  1514. * </pre>
  1515. *
  1516. * The default is not to display any unit in the denominator.
  1517. *
  1518. * If a per-unit is specified without a primary unit via {@link #unit}, the behavior is undefined.
  1519. *
  1520. * @param perUnit
  1521. * The unit to render in the denominator.
  1522. * @return The fluent chain
  1523. * @see #unit
  1524. * @stable ICU 61
  1525. */
  1526. Derived perUnit(const icu::MeasureUnit &perUnit) const &;
  1527. /**
  1528. * Overload of perUnit() for use on an rvalue reference.
  1529. *
  1530. * @param perUnit
  1531. * The unit to render in the denominator.
  1532. * @return The fluent chain.
  1533. * @see #perUnit
  1534. * @stable ICU 62
  1535. */
  1536. Derived perUnit(const icu::MeasureUnit &perUnit) &&;
  1537. /**
  1538. * Like perUnit(), but takes ownership of a pointer. Convenient for use with the MeasureFormat factory
  1539. * methods that return pointers that need ownership.
  1540. *
  1541. * Note: consider using the MeasureFormat factory methods that return by value.
  1542. *
  1543. * @param perUnit
  1544. * The unit to render in the denominator.
  1545. * @return The fluent chain.
  1546. * @see #perUnit
  1547. * @see MeasureUnit
  1548. * @stable ICU 61
  1549. */
  1550. Derived adoptPerUnit(icu::MeasureUnit *perUnit) const &;
  1551. /**
  1552. * Overload of adoptPerUnit() for use on an rvalue reference.
  1553. *
  1554. * @param perUnit
  1555. * The unit to render in the denominator.
  1556. * @return The fluent chain.
  1557. * @see #adoptPerUnit
  1558. * @stable ICU 62
  1559. */
  1560. Derived adoptPerUnit(icu::MeasureUnit *perUnit) &&;
  1561. /**
  1562. * Specifies the rounding precision to use when formatting numbers.
  1563. *
  1564. * <ul>
  1565. * <li>Round to 3 decimal places: "3.142"
  1566. * <li>Round to 3 significant figures: "3.14"
  1567. * <li>Round to the closest nickel: "3.15"
  1568. * <li>Do not perform rounding: "3.1415926..."
  1569. * </ul>
  1570. *
  1571. * <p>
  1572. * Pass this method the return value of one of the factory methods on {@link Precision}. For example:
  1573. *
  1574. * <pre>
  1575. * NumberFormatter::with().precision(Precision::fixedFraction(2))
  1576. * </pre>
  1577. *
  1578. * <p>
  1579. * In most cases, the default rounding strategy is to round to 6 fraction places; i.e.,
  1580. * <code>Precision.maxFraction(6)</code>. The exceptions are if compact notation is being used, then the compact
  1581. * notation rounding strategy is used (see {@link Notation#compactShort} for details), or if the unit is a currency,
  1582. * then standard currency rounding is used, which varies from currency to currency (see {@link Precision#currency} for
  1583. * details).
  1584. *
  1585. * @param precision
  1586. * The rounding precision to use.
  1587. * @return The fluent chain.
  1588. * @see Precision
  1589. * @stable ICU 62
  1590. */
  1591. Derived precision(const Precision& precision) const &;
  1592. /**
  1593. * Overload of precision() for use on an rvalue reference.
  1594. *
  1595. * @param precision
  1596. * The rounding precision to use.
  1597. * @return The fluent chain.
  1598. * @see #precision
  1599. * @stable ICU 62
  1600. */
  1601. Derived precision(const Precision& precision) &&;
  1602. /**
  1603. * Specifies how to determine the direction to round a number when it has more digits than fit in the
  1604. * desired precision. When formatting 1.235:
  1605. *
  1606. * <ul>
  1607. * <li>Ceiling rounding mode with integer precision: "2"
  1608. * <li>Half-down rounding mode with 2 fixed fraction digits: "1.23"
  1609. * <li>Half-up rounding mode with 2 fixed fraction digits: "1.24"
  1610. * </ul>
  1611. *
  1612. * The default is HALF_EVEN. For more information on rounding mode, see the ICU userguide here:
  1613. *
  1614. * https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes
  1615. *
  1616. * @param roundingMode The rounding mode to use.
  1617. * @return The fluent chain.
  1618. * @stable ICU 62
  1619. */
  1620. Derived roundingMode(UNumberFormatRoundingMode roundingMode) const &;
  1621. /**
  1622. * Overload of roundingMode() for use on an rvalue reference.
  1623. *
  1624. * @param roundingMode The rounding mode to use.
  1625. * @return The fluent chain.
  1626. * @see #roundingMode
  1627. * @stable ICU 62
  1628. */
  1629. Derived roundingMode(UNumberFormatRoundingMode roundingMode) &&;
  1630. /**
  1631. * Specifies the grouping strategy to use when formatting numbers.
  1632. *
  1633. * <ul>
  1634. * <li>Default grouping: "12,300" and "1,230"
  1635. * <li>Grouping with at least 2 digits: "12,300" and "1230"
  1636. * <li>No grouping: "12300" and "1230"
  1637. * </ul>
  1638. *
  1639. * <p>
  1640. * The exact grouping widths will be chosen based on the locale.
  1641. *
  1642. * <p>
  1643. * Pass this method an element from the {@link UNumberGroupingStrategy} enum. For example:
  1644. *
  1645. * <pre>
  1646. * NumberFormatter::with().grouping(UNUM_GROUPING_MIN2)
  1647. * </pre>
  1648. *
  1649. * The default is to perform grouping according to locale data; most locales, but not all locales,
  1650. * enable it by default.
  1651. *
  1652. * @param strategy
  1653. * The grouping strategy to use.
  1654. * @return The fluent chain.
  1655. * @stable ICU 61
  1656. */
  1657. Derived grouping(UNumberGroupingStrategy strategy) const &;
  1658. /**
  1659. * Overload of grouping() for use on an rvalue reference.
  1660. *
  1661. * @param strategy
  1662. * The grouping strategy to use.
  1663. * @return The fluent chain.
  1664. * @see #grouping
  1665. * @stable ICU 62
  1666. */
  1667. Derived grouping(UNumberGroupingStrategy strategy) &&;
  1668. /**
  1669. * Specifies the minimum and maximum number of digits to render before the decimal mark.
  1670. *
  1671. * <ul>
  1672. * <li>Zero minimum integer digits: ".08"
  1673. * <li>One minimum integer digit: "0.08"
  1674. * <li>Two minimum integer digits: "00.08"
  1675. * </ul>
  1676. *
  1677. * <p>
  1678. * Pass this method the return value of {@link IntegerWidth#zeroFillTo}. For example:
  1679. *
  1680. * <pre>
  1681. * NumberFormatter::with().integerWidth(IntegerWidth::zeroFillTo(2))
  1682. * </pre>
  1683. *
  1684. * The default is to have one minimum integer digit.
  1685. *
  1686. * @param style
  1687. * The integer width to use.
  1688. * @return The fluent chain.
  1689. * @see IntegerWidth
  1690. * @stable ICU 60
  1691. */
  1692. Derived integerWidth(const IntegerWidth &style) const &;
  1693. /**
  1694. * Overload of integerWidth() for use on an rvalue reference.
  1695. *
  1696. * @param style
  1697. * The integer width to use.
  1698. * @return The fluent chain.
  1699. * @see #integerWidth
  1700. * @stable ICU 62
  1701. */
  1702. Derived integerWidth(const IntegerWidth &style) &&;
  1703. /**
  1704. * Specifies the symbols (decimal separator, grouping separator, percent sign, numerals, etc.) to use when rendering
  1705. * numbers.
  1706. *
  1707. * <ul>
  1708. * <li><em>en_US</em> symbols: "12,345.67"
  1709. * <li><em>fr_FR</em> symbols: "12&nbsp;345,67"
  1710. * <li><em>de_CH</em> symbols: "12’345.67"
  1711. * <li><em>my_MY</em> symbols: "၁၂,၃၄၅.၆၇"
  1712. * </ul>
  1713. *
  1714. * <p>
  1715. * Pass this method an instance of {@link DecimalFormatSymbols}. For example:
  1716. *
  1717. * <pre>
  1718. * NumberFormatter::with().symbols(DecimalFormatSymbols(Locale("de_CH"), status))
  1719. * </pre>
  1720. *
  1721. * <p>
  1722. * <strong>Note:</strong> DecimalFormatSymbols automatically chooses the best numbering system based on the locale.
  1723. * In the examples above, the first three are using the Latin numbering system, and the fourth is using the Myanmar
  1724. * numbering system.
  1725. *
  1726. * <p>
  1727. * <strong>Note:</strong> The instance of DecimalFormatSymbols will be copied: changes made to the symbols object
  1728. * after passing it into the fluent chain will not be seen.
  1729. *
  1730. * <p>
  1731. * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
  1732. * or NumberingSystem.
  1733. *
  1734. * <p>
  1735. * The default is to choose the symbols based on the locale specified in the fluent chain.
  1736. *
  1737. * @param symbols
  1738. * The DecimalFormatSymbols to use.
  1739. * @return The fluent chain.
  1740. * @see DecimalFormatSymbols
  1741. * @stable ICU 60
  1742. */
  1743. Derived symbols(const DecimalFormatSymbols &symbols) const &;
  1744. /**
  1745. * Overload of symbols() for use on an rvalue reference.
  1746. *
  1747. * @param symbols
  1748. * The DecimalFormatSymbols to use.
  1749. * @return The fluent chain.
  1750. * @see #symbols
  1751. * @stable ICU 62
  1752. */
  1753. Derived symbols(const DecimalFormatSymbols &symbols) &&;
  1754. /**
  1755. * Specifies that the given numbering system should be used when fetching symbols.
  1756. *
  1757. * <ul>
  1758. * <li>Latin numbering system: "12,345"
  1759. * <li>Myanmar numbering system: "၁၂,၃၄၅"
  1760. * <li>Math Sans Bold numbering system: "𝟭𝟮,𝟯𝟰𝟱"
  1761. * </ul>
  1762. *
  1763. * <p>
  1764. * Pass this method an instance of {@link NumberingSystem}. For example, to force the locale to always use the Latin
  1765. * alphabet numbering system (ASCII digits):
  1766. *
  1767. * <pre>
  1768. * NumberFormatter::with().adoptSymbols(NumberingSystem::createInstanceByName("latn", status))
  1769. * </pre>
  1770. *
  1771. * <p>
  1772. * <strong>Note:</strong> Calling this method will override any previously specified DecimalFormatSymbols
  1773. * or NumberingSystem.
  1774. *
  1775. * <p>
  1776. * The default is to choose the best numbering system for the locale.
  1777. *
  1778. * <p>
  1779. * This method takes ownership of a pointer in order to work nicely with the NumberingSystem factory methods.
  1780. *
  1781. * @param symbols
  1782. * The NumberingSystem to use.
  1783. * @return The fluent chain.
  1784. * @see NumberingSystem
  1785. * @stable ICU 60
  1786. */
  1787. Derived adoptSymbols(NumberingSystem *symbols) const &;
  1788. /**
  1789. * Overload of adoptSymbols() for use on an rvalue reference.
  1790. *
  1791. * @param symbols
  1792. * The NumberingSystem to use.
  1793. * @return The fluent chain.
  1794. * @see #adoptSymbols
  1795. * @stable ICU 62
  1796. */
  1797. Derived adoptSymbols(NumberingSystem *symbols) &&;
  1798. /**
  1799. * Sets the width of the unit (measure unit or currency). Most common values:
  1800. *
  1801. * <ul>
  1802. * <li>Short: "$12.00", "12 m"
  1803. * <li>ISO Code: "USD 12.00"
  1804. * <li>Full name: "12.00 US dollars", "12 meters"
  1805. * </ul>
  1806. *
  1807. * <p>
  1808. * Pass an element from the {@link UNumberUnitWidth} enum to this setter. For example:
  1809. *
  1810. * <pre>
  1811. * NumberFormatter::with().unitWidth(UNumberUnitWidth::UNUM_UNIT_WIDTH_FULL_NAME)
  1812. * </pre>
  1813. *
  1814. * <p>
  1815. * The default is the SHORT width.
  1816. *
  1817. * @param width
  1818. * The width to use when rendering numbers.
  1819. * @return The fluent chain
  1820. * @see UNumberUnitWidth
  1821. * @stable ICU 60
  1822. */
  1823. Derived unitWidth(UNumberUnitWidth width) const &;
  1824. /**
  1825. * Overload of unitWidth() for use on an rvalue reference.
  1826. *
  1827. * @param width
  1828. * The width to use when rendering numbers.
  1829. * @return The fluent chain.
  1830. * @see #unitWidth
  1831. * @stable ICU 62
  1832. */
  1833. Derived unitWidth(UNumberUnitWidth width) &&;
  1834. /**
  1835. * Sets the plus/minus sign display strategy. Most common values:
  1836. *
  1837. * <ul>
  1838. * <li>Auto: "123", "-123"
  1839. * <li>Always: "+123", "-123"
  1840. * <li>Accounting: "$123", "($123)"
  1841. * </ul>
  1842. *
  1843. * <p>
  1844. * Pass an element from the {@link UNumberSignDisplay} enum to this setter. For example:
  1845. *
  1846. * <pre>
  1847. * NumberFormatter::with().sign(UNumberSignDisplay::UNUM_SIGN_ALWAYS)
  1848. * </pre>
  1849. *
  1850. * <p>
  1851. * The default is AUTO sign display.
  1852. *
  1853. * @param style
  1854. * The sign display strategy to use when rendering numbers.
  1855. * @return The fluent chain
  1856. * @see UNumberSignDisplay
  1857. * @stable ICU 60
  1858. */
  1859. Derived sign(UNumberSignDisplay style) const &;
  1860. /**
  1861. * Overload of sign() for use on an rvalue reference.
  1862. *
  1863. * @param style
  1864. * The sign display strategy to use when rendering numbers.
  1865. * @return The fluent chain.
  1866. * @see #sign
  1867. * @stable ICU 62
  1868. */
  1869. Derived sign(UNumberSignDisplay style) &&;
  1870. /**
  1871. * Sets the decimal separator display strategy. This affects integer numbers with no fraction part. Most common
  1872. * values:
  1873. *
  1874. * <ul>
  1875. * <li>Auto: "1"
  1876. * <li>Always: "1."
  1877. * </ul>
  1878. *
  1879. * <p>
  1880. * Pass an element from the {@link UNumberDecimalSeparatorDisplay} enum to this setter. For example:
  1881. *
  1882. * <pre>
  1883. * NumberFormatter::with().decimal(UNumberDecimalSeparatorDisplay::UNUM_DECIMAL_SEPARATOR_ALWAYS)
  1884. * </pre>
  1885. *
  1886. * <p>
  1887. * The default is AUTO decimal separator display.
  1888. *
  1889. * @param style
  1890. * The decimal separator display strategy to use when rendering numbers.
  1891. * @return The fluent chain
  1892. * @see UNumberDecimalSeparatorDisplay
  1893. * @stable ICU 60
  1894. */
  1895. Derived decimal(UNumberDecimalSeparatorDisplay style) const &;
  1896. /**
  1897. * Overload of decimal() for use on an rvalue reference.
  1898. *
  1899. * @param style
  1900. * The decimal separator display strategy to use when rendering numbers.
  1901. * @return The fluent chain.
  1902. * @see #decimal
  1903. * @stable ICU 62
  1904. */
  1905. Derived decimal(UNumberDecimalSeparatorDisplay style) &&;
  1906. /**
  1907. * Sets a scale (multiplier) to be used to scale the number by an arbitrary amount before formatting.
  1908. * Most common values:
  1909. *
  1910. * <ul>
  1911. * <li>Multiply by 100: useful for percentages.
  1912. * <li>Multiply by an arbitrary value: useful for unit conversions.
  1913. * </ul>
  1914. *
  1915. * <p>
  1916. * Pass an element from a {@link Scale} factory method to this setter. For example:
  1917. *
  1918. * <pre>
  1919. * NumberFormatter::with().scale(Scale::powerOfTen(2))
  1920. * </pre>
  1921. *
  1922. * <p>
  1923. * The default is to not apply any multiplier.
  1924. *
  1925. * @param scale
  1926. * The scale to apply when rendering numbers.
  1927. * @return The fluent chain
  1928. * @stable ICU 62
  1929. */
  1930. Derived scale(const Scale &scale) const &;
  1931. /**
  1932. * Overload of scale() for use on an rvalue reference.
  1933. *
  1934. * @param scale
  1935. * The scale to apply when rendering numbers.
  1936. * @return The fluent chain.
  1937. * @see #scale
  1938. * @stable ICU 62
  1939. */
  1940. Derived scale(const Scale &scale) &&;
  1941. /**
  1942. * Specifies the usage for which numbers will be formatted ("person-height",
  1943. * "road", "rainfall", etc.)
  1944. *
  1945. * When a `usage` is specified, the output unit will change depending on the
  1946. * `Locale` and the unit quantity. For example, formatting length
  1947. * measurements specified in meters:
  1948. *
  1949. * `NumberFormatter::with().usage("person").unit(MeasureUnit::getMeter()).locale("en-US")`
  1950. * * When formatting 0.25, the output will be "10 inches".
  1951. * * When formatting 1.50, the output will be "4 feet and 11 inches".
  1952. *
  1953. * The input unit specified via unit() determines the type of measurement
  1954. * being formatted (e.g. "length" when the unit is "foot"). The usage
  1955. * requested will be looked for only within this category of measurement
  1956. * units.
  1957. *
  1958. * The output unit can be found via FormattedNumber::getOutputUnit().
  1959. *
  1960. * If the usage has multiple parts (e.g. "land-agriculture-grain") and does
  1961. * not match a known usage preference, the last part will be dropped
  1962. * repeatedly until a match is found (e.g. trying "land-agriculture", then
  1963. * "land"). If a match is still not found, usage will fall back to
  1964. * "default".
  1965. *
  1966. * Setting usage to an empty string clears the usage (disables usage-based
  1967. * localized formatting).
  1968. *
  1969. * Setting a usage string but not a correct input unit will result in an
  1970. * U_ILLEGAL_ARGUMENT_ERROR.
  1971. *
  1972. * When using usage, specifying rounding or precision is unnecessary.
  1973. * Specifying a precision in some manner will override the default
  1974. * formatting.
  1975. *
  1976. * @param usage A `usage` parameter from the units resource. See the
  1977. * unitPreferenceData in *source/data/misc/units.txt*, generated from
  1978. * `unitPreferenceData` in [CLDR's
  1979. * supplemental/units.xml](https://github.com/unicode-org/cldr/blob/main/common/supplemental/units.xml).
  1980. * @return The fluent chain.
  1981. * @stable ICU 68
  1982. */
  1983. Derived usage(StringPiece usage) const &;
  1984. /**
  1985. * Overload of usage() for use on an rvalue reference.
  1986. *
  1987. * @param usage The unit `usage`.
  1988. * @return The fluent chain.
  1989. * @stable ICU 68
  1990. */
  1991. Derived usage(StringPiece usage) &&;
  1992. #ifndef U_HIDE_DRAFT_API
  1993. /**
  1994. * Specifies the DisplayOptions. For example, UDisplayOptionsGrammaticalCase specifies
  1995. * the desired case for a unit formatter's output (e.g. accusative, dative, genitive).
  1996. *
  1997. * @param displayOptions
  1998. * @return The fluent chain.
  1999. * @draft ICU 72
  2000. */
  2001. Derived displayOptions(const DisplayOptions &displayOptions) const &;
  2002. /**
  2003. * Overload of displayOptions() for use on an rvalue reference.
  2004. *
  2005. * @param displayOptions
  2006. * @return The fluent chain.
  2007. * @draft ICU 72
  2008. */
  2009. Derived displayOptions(const DisplayOptions &displayOptions) &&;
  2010. #endif // U_HIDE_DRAFT_API
  2011. #ifndef U_HIDE_INTERNAL_API
  2012. /**
  2013. * NOTE: Use `displayOptions` instead. This method was part of
  2014. * an internal technology preview in ICU 69, but will be removed
  2015. * in ICU 73, in favor of `displayOptions`
  2016. *
  2017. * Specifies the desired case for a unit formatter's output (e.g.
  2018. * accusative, dative, genitive).
  2019. *
  2020. * @internal
  2021. */
  2022. Derived unitDisplayCase(StringPiece unitDisplayCase) const &;
  2023. /**
  2024. * NOTE: Use `displayOptions` instead. This method was part of
  2025. * an internal technology preview in ICU 69, but will be removed
  2026. * in ICU 73, in favor of `displayOptions`
  2027. *
  2028. * Overload of unitDisplayCase() for use on an rvalue reference.
  2029. *
  2030. * @internal
  2031. */
  2032. Derived unitDisplayCase(StringPiece unitDisplayCase) &&;
  2033. #endif // U_HIDE_INTERNAL_API
  2034. #ifndef U_HIDE_INTERNAL_API
  2035. /**
  2036. * Set the padding strategy. May be added in the future; see #13338.
  2037. *
  2038. * @internal ICU 60: This API is ICU internal only.
  2039. */
  2040. Derived padding(const impl::Padder &padder) const &;
  2041. /** @internal */
  2042. Derived padding(const impl::Padder &padder) &&;
  2043. /**
  2044. * Internal fluent setter to support a custom regulation threshold. A threshold of 1 causes the data structures to
  2045. * be built right away. A threshold of 0 prevents the data structures from being built.
  2046. *
  2047. * @internal ICU 60: This API is ICU internal only.
  2048. */
  2049. Derived threshold(int32_t threshold) const &;
  2050. /** @internal */
  2051. Derived threshold(int32_t threshold) &&;
  2052. /**
  2053. * Internal fluent setter to overwrite the entire macros object.
  2054. *
  2055. * @internal ICU 60: This API is ICU internal only.
  2056. */
  2057. Derived macros(const impl::MacroProps& macros) const &;
  2058. /** @internal */
  2059. Derived macros(const impl::MacroProps& macros) &&;
  2060. /** @internal */
  2061. Derived macros(impl::MacroProps&& macros) const &;
  2062. /** @internal */
  2063. Derived macros(impl::MacroProps&& macros) &&;
  2064. #endif /* U_HIDE_INTERNAL_API */
  2065. /**
  2066. * Creates a skeleton string representation of this number formatter. A skeleton string is a
  2067. * locale-agnostic serialized form of a number formatter.
  2068. *
  2069. * Not all options are capable of being represented in the skeleton string; for example, a
  2070. * DecimalFormatSymbols object. If any such option is encountered, the error code is set to
  2071. * U_UNSUPPORTED_ERROR.
  2072. *
  2073. * The returned skeleton is in normalized form, such that two number formatters with equivalent
  2074. * behavior should produce the same skeleton.
  2075. *
  2076. * For more information on number skeleton strings, see:
  2077. * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
  2078. *
  2079. * @return A number skeleton string with behavior corresponding to this number formatter.
  2080. * @stable ICU 62
  2081. */
  2082. UnicodeString toSkeleton(UErrorCode& status) const;
  2083. /**
  2084. * Returns the current (Un)LocalizedNumberFormatter as a LocalPointer
  2085. * wrapping a heap-allocated copy of the current object.
  2086. *
  2087. * This is equivalent to new-ing the move constructor with a value object
  2088. * as the argument.
  2089. *
  2090. * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
  2091. * nullptr on failure.
  2092. * @stable ICU 64
  2093. */
  2094. LocalPointer<Derived> clone() const &;
  2095. /**
  2096. * Overload of clone for use on an rvalue reference.
  2097. *
  2098. * @return A wrapped (Un)LocalizedNumberFormatter pointer, or a wrapped
  2099. * nullptr on failure.
  2100. * @stable ICU 64
  2101. */
  2102. LocalPointer<Derived> clone() &&;
  2103. /**
  2104. * Sets the UErrorCode if an error occurred in the fluent chain.
  2105. * Preserves older error codes in the outErrorCode.
  2106. * @return true if U_FAILURE(outErrorCode)
  2107. * @stable ICU 60
  2108. */
  2109. UBool copyErrorTo(UErrorCode &outErrorCode) const {
  2110. if (U_FAILURE(outErrorCode)) {
  2111. // Do not overwrite the older error code
  2112. return true;
  2113. }
  2114. fMacros.copyErrorTo(outErrorCode);
  2115. return U_FAILURE(outErrorCode);
  2116. }
  2117. // NOTE: Uses default copy and move constructors.
  2118. private:
  2119. impl::MacroProps fMacros;
  2120. // Don't construct me directly! Use (Un)LocalizedNumberFormatter.
  2121. NumberFormatterSettings() = default;
  2122. friend class LocalizedNumberFormatter;
  2123. friend class UnlocalizedNumberFormatter;
  2124. // Give NumberRangeFormatter access to the MacroProps
  2125. friend void impl::touchRangeLocales(impl::RangeMacroProps& macros);
  2126. friend class impl::NumberRangeFormatterImpl;
  2127. };
  2128. // Explicit instantiations in source/i18n/number_fluent.cpp.
  2129. // (MSVC treats imports/exports of explicit instantiations differently.)
  2130. #ifndef _MSC_VER
  2131. extern template class NumberFormatterSettings<UnlocalizedNumberFormatter>;
  2132. extern template class NumberFormatterSettings<LocalizedNumberFormatter>;
  2133. #endif
  2134. /**
  2135. * A NumberFormatter that does not yet have a locale. In order to format numbers, a locale must be specified.
  2136. *
  2137. * Instances of this class are immutable and thread-safe.
  2138. *
  2139. * @see NumberFormatter
  2140. * @stable ICU 60
  2141. */
  2142. class U_I18N_API UnlocalizedNumberFormatter
  2143. : public NumberFormatterSettings<UnlocalizedNumberFormatter>, public UMemory {
  2144. public:
  2145. /**
  2146. * Associate the given locale with the number formatter. The locale is used for picking the appropriate symbols,
  2147. * formats, and other data for number display.
  2148. *
  2149. * @param locale
  2150. * The locale to use when loading data for number formatting.
  2151. * @return The fluent chain.
  2152. * @stable ICU 60
  2153. */
  2154. LocalizedNumberFormatter locale(const icu::Locale &locale) const &;
  2155. /**
  2156. * Overload of locale() for use on an rvalue reference.
  2157. *
  2158. * @param locale
  2159. * The locale to use when loading data for number formatting.
  2160. * @return The fluent chain.
  2161. * @see #locale
  2162. * @stable ICU 62
  2163. */
  2164. LocalizedNumberFormatter locale(const icu::Locale &locale) &&;
  2165. /**
  2166. * Default constructor: puts the formatter into a valid but undefined state.
  2167. *
  2168. * @stable ICU 62
  2169. */
  2170. UnlocalizedNumberFormatter() = default;
  2171. /**
  2172. * Returns a copy of this UnlocalizedNumberFormatter.
  2173. * @stable ICU 60
  2174. */
  2175. UnlocalizedNumberFormatter(const UnlocalizedNumberFormatter &other);
  2176. /**
  2177. * Move constructor:
  2178. * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
  2179. * @stable ICU 62
  2180. */
  2181. UnlocalizedNumberFormatter(UnlocalizedNumberFormatter&& src) noexcept;
  2182. /**
  2183. * Copy assignment operator.
  2184. * @stable ICU 62
  2185. */
  2186. UnlocalizedNumberFormatter& operator=(const UnlocalizedNumberFormatter& other);
  2187. /**
  2188. * Move assignment operator:
  2189. * The source UnlocalizedNumberFormatter will be left in a valid but undefined state.
  2190. * @stable ICU 62
  2191. */
  2192. UnlocalizedNumberFormatter& operator=(UnlocalizedNumberFormatter&& src) noexcept;
  2193. private:
  2194. explicit UnlocalizedNumberFormatter(const NumberFormatterSettings<UnlocalizedNumberFormatter>& other);
  2195. explicit UnlocalizedNumberFormatter(
  2196. NumberFormatterSettings<UnlocalizedNumberFormatter>&& src) noexcept;
  2197. // To give the fluent setters access to this class's constructor:
  2198. friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
  2199. // To give NumberFormatter::with() access to this class's constructor:
  2200. friend class NumberFormatter;
  2201. };
  2202. /**
  2203. * A NumberFormatter that has a locale associated with it; this means .format() methods are available.
  2204. *
  2205. * Instances of this class are immutable and thread-safe.
  2206. *
  2207. * @see NumberFormatter
  2208. * @stable ICU 60
  2209. */
  2210. class U_I18N_API LocalizedNumberFormatter
  2211. : public NumberFormatterSettings<LocalizedNumberFormatter>, public UMemory {
  2212. public:
  2213. /**
  2214. * Format the given integer number to a string using the settings specified in the NumberFormatter fluent
  2215. * setting chain.
  2216. *
  2217. * @param value
  2218. * The number to format.
  2219. * @param status
  2220. * Set to an ErrorCode if one occurred in the setter chain or during formatting.
  2221. * @return A FormattedNumber object; call .toString() to get the string.
  2222. * @stable ICU 60
  2223. */
  2224. FormattedNumber formatInt(int64_t value, UErrorCode &status) const;
  2225. /**
  2226. * Format the given float or double to a string using the settings specified in the NumberFormatter fluent setting
  2227. * chain.
  2228. *
  2229. * @param value
  2230. * The number to format.
  2231. * @param status
  2232. * Set to an ErrorCode if one occurred in the setter chain or during formatting.
  2233. * @return A FormattedNumber object; call .toString() to get the string.
  2234. * @stable ICU 60
  2235. */
  2236. FormattedNumber formatDouble(double value, UErrorCode &status) const;
  2237. /**
  2238. * Format the given decimal number to a string using the settings
  2239. * specified in the NumberFormatter fluent setting chain.
  2240. * The syntax of the unformatted number is a "numeric string"
  2241. * as defined in the Decimal Arithmetic Specification, available at
  2242. * http://speleotrove.com/decimal
  2243. *
  2244. * @param value
  2245. * The number to format.
  2246. * @param status
  2247. * Set to an ErrorCode if one occurred in the setter chain or during formatting.
  2248. * @return A FormattedNumber object; call .toString() to get the string.
  2249. * @stable ICU 60
  2250. */
  2251. FormattedNumber formatDecimal(StringPiece value, UErrorCode& status) const;
  2252. #ifndef U_HIDE_INTERNAL_API
  2253. /**
  2254. * @internal
  2255. */
  2256. const DecimalFormatSymbols* getDecimalFormatSymbols() const;
  2257. /** Internal method.
  2258. * @internal
  2259. */
  2260. FormattedNumber formatDecimalQuantity(const impl::DecimalQuantity& dq, UErrorCode& status) const;
  2261. /** Internal method for DecimalFormat compatibility.
  2262. * @internal
  2263. */
  2264. void getAffixImpl(bool isPrefix, bool isNegative, UnicodeString& result, UErrorCode& status) const;
  2265. /**
  2266. * Internal method for testing.
  2267. * @internal
  2268. */
  2269. const impl::NumberFormatterImpl* getCompiled() const;
  2270. /**
  2271. * Internal method for testing.
  2272. * @internal
  2273. */
  2274. int32_t getCallCount() const;
  2275. #endif /* U_HIDE_INTERNAL_API */
  2276. /**
  2277. * Creates a representation of this LocalizedNumberFormat as an icu::Format, enabling the use
  2278. * of this number formatter with APIs that need an object of that type, such as MessageFormat.
  2279. *
  2280. * This API is not intended to be used other than for enabling API compatibility. The formatDouble,
  2281. * formatInt, and formatDecimal methods should normally be used when formatting numbers, not the Format
  2282. * object returned by this method.
  2283. *
  2284. * The caller owns the returned object and must delete it when finished.
  2285. *
  2286. * @return A Format wrapping this LocalizedNumberFormatter.
  2287. * @stable ICU 62
  2288. */
  2289. Format* toFormat(UErrorCode& status) const;
  2290. /**
  2291. * Default constructor: puts the formatter into a valid but undefined state.
  2292. *
  2293. * @stable ICU 62
  2294. */
  2295. LocalizedNumberFormatter() = default;
  2296. /**
  2297. * Returns a copy of this LocalizedNumberFormatter.
  2298. * @stable ICU 60
  2299. */
  2300. LocalizedNumberFormatter(const LocalizedNumberFormatter &other);
  2301. /**
  2302. * Move constructor:
  2303. * The source LocalizedNumberFormatter will be left in a valid but undefined state.
  2304. * @stable ICU 62
  2305. */
  2306. LocalizedNumberFormatter(LocalizedNumberFormatter&& src) noexcept;
  2307. /**
  2308. * Copy assignment operator.
  2309. * @stable ICU 62
  2310. */
  2311. LocalizedNumberFormatter& operator=(const LocalizedNumberFormatter& other);
  2312. /**
  2313. * Move assignment operator:
  2314. * The source LocalizedNumberFormatter will be left in a valid but undefined state.
  2315. * @stable ICU 62
  2316. */
  2317. LocalizedNumberFormatter& operator=(LocalizedNumberFormatter&& src) noexcept;
  2318. #ifndef U_HIDE_INTERNAL_API
  2319. /**
  2320. * This is the core entrypoint to the number formatting pipeline. It performs self-regulation: a static code path
  2321. * for the first few calls, and compiling a more efficient data structure if called repeatedly.
  2322. *
  2323. * <p>
  2324. * This function is very hot, being called in every call to the number formatting pipeline.
  2325. *
  2326. * @param results
  2327. * The results object. This method will mutate it to save the results.
  2328. * @param status
  2329. * @internal
  2330. */
  2331. void formatImpl(impl::UFormattedNumberData *results, UErrorCode &status) const;
  2332. #endif /* U_HIDE_INTERNAL_API */
  2333. /**
  2334. * Destruct this LocalizedNumberFormatter, cleaning up any memory it might own.
  2335. * @stable ICU 60
  2336. */
  2337. ~LocalizedNumberFormatter();
  2338. private:
  2339. // Note: fCompiled can't be a LocalPointer because impl::NumberFormatterImpl is defined in an internal
  2340. // header, and LocalPointer needs the full class definition in order to delete the instance.
  2341. const impl::NumberFormatterImpl* fCompiled {nullptr};
  2342. char fUnsafeCallCount[8] {}; // internally cast to u_atomic_int32_t
  2343. // Owned pointer to a DecimalFormatWarehouse, used when copying a LocalizedNumberFormatter
  2344. // from a DecimalFormat.
  2345. const impl::DecimalFormatWarehouse* fWarehouse {nullptr};
  2346. explicit LocalizedNumberFormatter(const NumberFormatterSettings<LocalizedNumberFormatter>& other);
  2347. explicit LocalizedNumberFormatter(NumberFormatterSettings<LocalizedNumberFormatter>&& src) noexcept;
  2348. LocalizedNumberFormatter(const impl::MacroProps &macros, const Locale &locale);
  2349. LocalizedNumberFormatter(impl::MacroProps &&macros, const Locale &locale);
  2350. void resetCompiled();
  2351. void lnfMoveHelper(LocalizedNumberFormatter&& src);
  2352. void lnfCopyHelper(const LocalizedNumberFormatter& src, UErrorCode& status);
  2353. /**
  2354. * @return true if the compiled formatter is available.
  2355. */
  2356. bool computeCompiled(UErrorCode& status) const;
  2357. // To give the fluent setters access to this class's constructor:
  2358. friend class NumberFormatterSettings<UnlocalizedNumberFormatter>;
  2359. friend class NumberFormatterSettings<LocalizedNumberFormatter>;
  2360. // To give UnlocalizedNumberFormatter::locale() access to this class's constructor:
  2361. friend class UnlocalizedNumberFormatter;
  2362. };
  2363. #if (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN) && defined(_MSC_VER)
  2364. // Warning 4661.
  2365. #pragma warning(pop)
  2366. #endif
  2367. /**
  2368. * See the main description in numberformatter.h for documentation and examples.
  2369. *
  2370. * @stable ICU 60
  2371. */
  2372. class U_I18N_API NumberFormatter final {
  2373. public:
  2374. /**
  2375. * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is not currently known at
  2376. * the call site.
  2377. *
  2378. * @return An {@link UnlocalizedNumberFormatter}, to be used for chaining.
  2379. * @stable ICU 60
  2380. */
  2381. static UnlocalizedNumberFormatter with();
  2382. /**
  2383. * Call this method at the beginning of a NumberFormatter fluent chain in which the locale is known at the call
  2384. * site.
  2385. *
  2386. * @param locale
  2387. * The locale from which to load formats and symbols for number formatting.
  2388. * @return A {@link LocalizedNumberFormatter}, to be used for chaining.
  2389. * @stable ICU 60
  2390. */
  2391. static LocalizedNumberFormatter withLocale(const Locale &locale);
  2392. /**
  2393. * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
  2394. * on a given number skeleton string.
  2395. *
  2396. * It is possible for an error to occur while parsing. See the overload of this method if you are
  2397. * interested in the location of a possible parse error.
  2398. *
  2399. * For more information on number skeleton strings, see:
  2400. * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
  2401. *
  2402. * @param skeleton
  2403. * The skeleton string off of which to base this NumberFormatter.
  2404. * @param status
  2405. * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
  2406. * @return An UnlocalizedNumberFormatter, to be used for chaining.
  2407. * @stable ICU 62
  2408. */
  2409. static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton, UErrorCode& status);
  2410. /**
  2411. * Call this method at the beginning of a NumberFormatter fluent chain to create an instance based
  2412. * on a given number skeleton string.
  2413. *
  2414. * If an error occurs while parsing the skeleton string, the offset into the skeleton string at
  2415. * which the error occurred will be saved into the UParseError, if provided.
  2416. *
  2417. * For more information on number skeleton strings, see:
  2418. * https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
  2419. *
  2420. * @param skeleton
  2421. * The skeleton string off of which to base this NumberFormatter.
  2422. * @param perror
  2423. * A parse error struct populated if an error occurs when parsing.
  2424. * If no error occurs, perror.offset will be set to -1.
  2425. * @param status
  2426. * Set to U_NUMBER_SKELETON_SYNTAX_ERROR if the skeleton was invalid.
  2427. * @return An UnlocalizedNumberFormatter, to be used for chaining.
  2428. * @stable ICU 64
  2429. */
  2430. static UnlocalizedNumberFormatter forSkeleton(const UnicodeString& skeleton,
  2431. UParseError& perror, UErrorCode& status);
  2432. /**
  2433. * Use factory methods instead of the constructor to create a NumberFormatter.
  2434. */
  2435. NumberFormatter() = delete;
  2436. };
  2437. } // namespace number
  2438. U_NAMESPACE_END
  2439. #endif /* #if !UCONFIG_NO_FORMATTING */
  2440. #endif /* U_SHOW_CPLUSPLUS_API */
  2441. #endif // __NUMBERFORMATTER_H__