numberformatter.h 91 KB

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