NumberFormat.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. /*
  2. * Copyright (c) 2021-2022, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Utf8View.h>
  7. #include <LibJS/Runtime/Array.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Intl/NumberFormat.h>
  10. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  11. #include <LibUnicode/CurrencyCode.h>
  12. #include <math.h>
  13. #include <stdlib.h>
  14. namespace JS::Intl {
  15. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  16. NumberFormat::NumberFormat(Object& prototype)
  17. : Object(prototype)
  18. {
  19. }
  20. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  21. {
  22. Base::visit_edges(visitor);
  23. if (m_bound_format)
  24. visitor.visit(m_bound_format);
  25. }
  26. void NumberFormat::set_style(StringView style)
  27. {
  28. if (style == "decimal"sv)
  29. m_style = Style::Decimal;
  30. else if (style == "percent"sv)
  31. m_style = Style::Percent;
  32. else if (style == "currency"sv)
  33. m_style = Style::Currency;
  34. else if (style == "unit"sv)
  35. m_style = Style::Unit;
  36. else
  37. VERIFY_NOT_REACHED();
  38. }
  39. StringView NumberFormat::style_string() const
  40. {
  41. switch (m_style) {
  42. case Style::Decimal:
  43. return "decimal"sv;
  44. case Style::Percent:
  45. return "percent"sv;
  46. case Style::Currency:
  47. return "currency"sv;
  48. case Style::Unit:
  49. return "unit"sv;
  50. default:
  51. VERIFY_NOT_REACHED();
  52. }
  53. }
  54. void NumberFormat::set_currency_display(StringView currency_display)
  55. {
  56. m_resolved_currency_display.clear();
  57. if (currency_display == "code"sv)
  58. m_currency_display = CurrencyDisplay::Code;
  59. else if (currency_display == "symbol"sv)
  60. m_currency_display = CurrencyDisplay::Symbol;
  61. else if (currency_display == "narrowSymbol"sv)
  62. m_currency_display = CurrencyDisplay::NarrowSymbol;
  63. else if (currency_display == "name"sv)
  64. m_currency_display = CurrencyDisplay::Name;
  65. else
  66. VERIFY_NOT_REACHED();
  67. }
  68. StringView NumberFormat::resolve_currency_display()
  69. {
  70. if (m_resolved_currency_display.has_value())
  71. return *m_resolved_currency_display;
  72. switch (currency_display()) {
  73. case NumberFormat::CurrencyDisplay::Code:
  74. m_resolved_currency_display = currency();
  75. break;
  76. case NumberFormat::CurrencyDisplay::Symbol:
  77. m_resolved_currency_display = Unicode::get_locale_short_currency_mapping(data_locale(), currency());
  78. break;
  79. case NumberFormat::CurrencyDisplay::NarrowSymbol:
  80. m_resolved_currency_display = Unicode::get_locale_narrow_currency_mapping(data_locale(), currency());
  81. break;
  82. case NumberFormat::CurrencyDisplay::Name:
  83. m_resolved_currency_display = Unicode::get_locale_numeric_currency_mapping(data_locale(), currency());
  84. break;
  85. default:
  86. VERIFY_NOT_REACHED();
  87. }
  88. if (!m_resolved_currency_display.has_value())
  89. m_resolved_currency_display = currency();
  90. return *m_resolved_currency_display;
  91. }
  92. StringView NumberFormat::currency_display_string() const
  93. {
  94. VERIFY(m_currency_display.has_value());
  95. switch (*m_currency_display) {
  96. case CurrencyDisplay::Code:
  97. return "code"sv;
  98. case CurrencyDisplay::Symbol:
  99. return "symbol"sv;
  100. case CurrencyDisplay::NarrowSymbol:
  101. return "narrowSymbol"sv;
  102. case CurrencyDisplay::Name:
  103. return "name"sv;
  104. default:
  105. VERIFY_NOT_REACHED();
  106. }
  107. }
  108. void NumberFormat::set_currency_sign(StringView currency_sign)
  109. {
  110. if (currency_sign == "standard"sv)
  111. m_currency_sign = CurrencySign::Standard;
  112. else if (currency_sign == "accounting"sv)
  113. m_currency_sign = CurrencySign::Accounting;
  114. else
  115. VERIFY_NOT_REACHED();
  116. }
  117. StringView NumberFormat::currency_sign_string() const
  118. {
  119. VERIFY(m_currency_sign.has_value());
  120. switch (*m_currency_sign) {
  121. case CurrencySign::Standard:
  122. return "standard"sv;
  123. case CurrencySign::Accounting:
  124. return "accounting"sv;
  125. default:
  126. VERIFY_NOT_REACHED();
  127. }
  128. }
  129. StringView NumberFormat::rounding_type_string() const
  130. {
  131. switch (m_rounding_type) {
  132. case RoundingType::SignificantDigits:
  133. return "significantDigits"sv;
  134. case RoundingType::FractionDigits:
  135. return "fractionDigits"sv;
  136. case RoundingType::CompactRounding:
  137. return "compactRounding"sv;
  138. default:
  139. VERIFY_NOT_REACHED();
  140. }
  141. }
  142. void NumberFormat::set_notation(StringView notation)
  143. {
  144. if (notation == "standard"sv)
  145. m_notation = Notation::Standard;
  146. else if (notation == "scientific"sv)
  147. m_notation = Notation::Scientific;
  148. else if (notation == "engineering"sv)
  149. m_notation = Notation::Engineering;
  150. else if (notation == "compact"sv)
  151. m_notation = Notation::Compact;
  152. else
  153. VERIFY_NOT_REACHED();
  154. }
  155. StringView NumberFormat::notation_string() const
  156. {
  157. switch (m_notation) {
  158. case Notation::Standard:
  159. return "standard"sv;
  160. case Notation::Scientific:
  161. return "scientific"sv;
  162. case Notation::Engineering:
  163. return "engineering"sv;
  164. case Notation::Compact:
  165. return "compact"sv;
  166. default:
  167. VERIFY_NOT_REACHED();
  168. }
  169. }
  170. void NumberFormat::set_compact_display(StringView compact_display)
  171. {
  172. if (compact_display == "short"sv)
  173. m_compact_display = CompactDisplay::Short;
  174. else if (compact_display == "long"sv)
  175. m_compact_display = CompactDisplay::Long;
  176. else
  177. VERIFY_NOT_REACHED();
  178. }
  179. StringView NumberFormat::compact_display_string() const
  180. {
  181. VERIFY(m_compact_display.has_value());
  182. switch (*m_compact_display) {
  183. case CompactDisplay::Short:
  184. return "short"sv;
  185. case CompactDisplay::Long:
  186. return "long"sv;
  187. default:
  188. VERIFY_NOT_REACHED();
  189. }
  190. }
  191. void NumberFormat::set_sign_display(StringView sign_display)
  192. {
  193. if (sign_display == "auto"sv)
  194. m_sign_display = SignDisplay::Auto;
  195. else if (sign_display == "never"sv)
  196. m_sign_display = SignDisplay::Never;
  197. else if (sign_display == "always"sv)
  198. m_sign_display = SignDisplay::Always;
  199. else if (sign_display == "exceptZero"sv)
  200. m_sign_display = SignDisplay::ExceptZero;
  201. else
  202. VERIFY_NOT_REACHED();
  203. }
  204. StringView NumberFormat::sign_display_string() const
  205. {
  206. switch (m_sign_display) {
  207. case SignDisplay::Auto:
  208. return "auto"sv;
  209. case SignDisplay::Never:
  210. return "never"sv;
  211. case SignDisplay::Always:
  212. return "always"sv;
  213. case SignDisplay::ExceptZero:
  214. return "exceptZero"sv;
  215. default:
  216. VERIFY_NOT_REACHED();
  217. }
  218. }
  219. static ALWAYS_INLINE int log10floor(double value)
  220. {
  221. return static_cast<int>(floor(log10(value)));
  222. }
  223. // 15.1.1 SetNumberFormatDigitOptions ( intlObj, options, mnfdDefault, mxfdDefault, notation ), https://tc39.es/ecma402/#sec-setnfdigitoptions
  224. ThrowCompletionOr<void> set_number_format_digit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options, int default_min_fraction_digits, int default_max_fraction_digits, NumberFormat::Notation notation)
  225. {
  226. auto& vm = global_object.vm();
  227. // 1. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1).
  228. auto min_integer_digits = TRY(get_number_option(global_object, options, vm.names.minimumIntegerDigits, 1, 21, 1));
  229. // 2. Let mnfd be ? Get(options, "minimumFractionDigits").
  230. auto min_fraction_digits = TRY(options.get(vm.names.minimumFractionDigits));
  231. // 3. Let mxfd be ? Get(options, "maximumFractionDigits").
  232. auto max_fraction_digits = TRY(options.get(vm.names.maximumFractionDigits));
  233. // 4. Let mnsd be ? Get(options, "minimumSignificantDigits").
  234. auto min_significant_digits = TRY(options.get(vm.names.minimumSignificantDigits));
  235. // 5. Let mxsd be ? Get(options, "maximumSignificantDigits").
  236. auto max_significant_digits = TRY(options.get(vm.names.maximumSignificantDigits));
  237. // 6. Set intlObj.[[MinimumIntegerDigits]] to mnid.
  238. intl_object.set_min_integer_digits(*min_integer_digits);
  239. // 7. If mnsd is not undefined or mxsd is not undefined, then
  240. // a. Let hasSd be true.
  241. // 8. Else,
  242. // a. Let hasSd be false.
  243. bool has_significant_digits = !min_significant_digits.is_undefined() || !max_significant_digits.is_undefined();
  244. // 9. If mnfd is not undefined or mxfd is not undefined, then
  245. // a. Let hasFd be true.
  246. // 10. Else,
  247. // a. Let hasFd be false.
  248. bool has_fraction_digits = !min_fraction_digits.is_undefined() || !max_fraction_digits.is_undefined();
  249. // 11. Let needSd be hasSd.
  250. bool need_significant_digits = has_significant_digits;
  251. // 12. If hasSd is true, or hasFd is false and notation is "compact", then
  252. // a. Let needFd be false.
  253. // 13. Else,
  254. // a. Let needFd be true.
  255. bool need_fraction_digits = !has_significant_digits && (has_fraction_digits || (notation != NumberFormat::Notation::Compact));
  256. // 14. If needSd is true, then
  257. if (need_significant_digits) {
  258. // a. Assert: hasSd is true.
  259. VERIFY(has_significant_digits);
  260. // b. Set mnsd to ? DefaultNumberOption(mnsd, 1, 21, 1).
  261. auto min_digits = TRY(default_number_option(global_object, min_significant_digits, 1, 21, 1));
  262. // c. Set mxsd to ? DefaultNumberOption(mxsd, mnsd, 21, 21).
  263. auto max_digits = TRY(default_number_option(global_object, max_significant_digits, *min_digits, 21, 21));
  264. // d. Set intlObj.[[MinimumSignificantDigits]] to mnsd.
  265. intl_object.set_min_significant_digits(*min_digits);
  266. // e. Set intlObj.[[MaximumSignificantDigits]] to mxsd.
  267. intl_object.set_max_significant_digits(*max_digits);
  268. }
  269. // 15. If needFd is true, then
  270. if (need_fraction_digits) {
  271. // a. If hasFd is true, then
  272. if (has_fraction_digits) {
  273. // i. Set mnfd to ? DefaultNumberOption(mnfd, 0, 20, undefined).
  274. auto min_digits = TRY(default_number_option(global_object, min_fraction_digits, 0, 20, {}));
  275. // ii. Set mxfd to ? DefaultNumberOption(mxfd, 0, 20, undefined).
  276. auto max_digits = TRY(default_number_option(global_object, max_fraction_digits, 0, 20, {}));
  277. // iii. If mnfd is undefined, set mnfd to min(mnfdDefault, mxfd).
  278. if (!min_digits.has_value())
  279. min_digits = min(default_min_fraction_digits, *max_digits);
  280. // iv. Else if mxfd is undefined, set mxfd to max(mxfdDefault, mnfd).
  281. else if (!max_digits.has_value())
  282. max_digits = max(default_max_fraction_digits, *min_digits);
  283. // v. Else if mnfd is greater than mxfd, throw a RangeError exception.
  284. else if (*min_digits > *max_digits)
  285. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlMinimumExceedsMaximum, *min_digits, *max_digits);
  286. // vi. Set intlObj.[[MinimumFractionDigits]] to mnfd.
  287. intl_object.set_min_fraction_digits(*min_digits);
  288. // vii. Set intlObj.[[MaximumFractionDigits]] to mxfd.
  289. intl_object.set_max_fraction_digits(*max_digits);
  290. }
  291. // b. Else,
  292. else {
  293. // i. Set intlObj.[[MinimumFractionDigits]] to mnfdDefault.
  294. intl_object.set_min_fraction_digits(default_min_fraction_digits);
  295. // ii. Set intlObj.[[MaximumFractionDigits]] to mxfdDefault.
  296. intl_object.set_max_fraction_digits(default_max_fraction_digits);
  297. }
  298. }
  299. // 16. If needSd is false and needFd is false, then
  300. if (!need_significant_digits && !need_fraction_digits) {
  301. // a. Set intlObj.[[RoundingType]] to compactRounding.
  302. intl_object.set_rounding_type(NumberFormat::RoundingType::CompactRounding);
  303. }
  304. // 17. Else if hasSd is true, then
  305. else if (has_significant_digits) {
  306. // a. Set intlObj.[[RoundingType]] to significantDigits.
  307. intl_object.set_rounding_type(NumberFormat::RoundingType::SignificantDigits);
  308. }
  309. // 18. Else,
  310. else {
  311. // a. Set intlObj.[[RoundingType]] to fractionDigits.
  312. intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
  313. }
  314. return {};
  315. }
  316. // 15.1.2 InitializeNumberFormat ( numberFormat, locales, options ), https://tc39.es/ecma402/#sec-initializenumberformat
  317. ThrowCompletionOr<NumberFormat*> initialize_number_format(GlobalObject& global_object, NumberFormat& number_format, Value locales_value, Value options_value)
  318. {
  319. auto& vm = global_object.vm();
  320. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  321. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  322. // 2. Set options to ? CoerceOptionsToObject(options).
  323. auto* options = TRY(coerce_options_to_object(global_object, options_value));
  324. // 3. Let opt be a new Record.
  325. LocaleOptions opt {};
  326. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  327. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv));
  328. // 5. Set opt.[[localeMatcher]] to matcher.
  329. opt.locale_matcher = matcher;
  330. // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  331. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  332. // 7. If numberingSystem is not undefined, then
  333. if (!numbering_system.is_undefined()) {
  334. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  335. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  336. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  337. // 8. Set opt.[[nu]] to numberingSystem.
  338. opt.nu = numbering_system.as_string().string();
  339. }
  340. // 9. Let localeData be %NumberFormat%.[[LocaleData]].
  341. // 10. Let r be ResolveLocale(%NumberFormat%.[[AvailableLocales]], requestedLocales, opt, %NumberFormat%.[[RelevantExtensionKeys]], localeData).
  342. auto result = resolve_locale(requested_locales, opt, NumberFormat::relevant_extension_keys());
  343. // 11. Set numberFormat.[[Locale]] to r.[[locale]].
  344. number_format.set_locale(move(result.locale));
  345. // 12. Set numberFormat.[[DataLocale]] to r.[[dataLocale]].
  346. number_format.set_data_locale(move(result.data_locale));
  347. // 13. Set numberFormat.[[NumberingSystem]] to r.[[nu]].
  348. if (result.nu.has_value())
  349. number_format.set_numbering_system(result.nu.release_value());
  350. // 14. Perform ? SetNumberFormatUnitOptions(numberFormat, options).
  351. TRY(set_number_format_unit_options(global_object, number_format, *options));
  352. // 15. Let style be numberFormat.[[Style]].
  353. auto style = number_format.style();
  354. int default_min_fraction_digits = 0;
  355. int default_max_fraction_digits = 0;
  356. // 16. If style is "currency", then
  357. if (style == NumberFormat::Style::Currency) {
  358. // a. Let currency be numberFormat.[[Currency]].
  359. auto const& currency = number_format.currency();
  360. // b. Let cDigits be CurrencyDigits(currency).
  361. int digits = currency_digits(currency);
  362. // c. Let mnfdDefault be cDigits.
  363. default_min_fraction_digits = digits;
  364. // d. Let mxfdDefault be cDigits.
  365. default_max_fraction_digits = digits;
  366. }
  367. // 17. Else,
  368. else {
  369. // a. Let mnfdDefault be 0.
  370. default_min_fraction_digits = 0;
  371. // b. If style is "percent", then
  372. // i. Let mxfdDefault be 0.
  373. // c. Else,
  374. // i. Let mxfdDefault be 3.
  375. default_max_fraction_digits = style == NumberFormat::Style::Percent ? 0 : 3;
  376. }
  377. // 18. Let notation be ? GetOption(options, "notation", "string", « "standard", "scientific", "engineering", "compact" », "standard").
  378. auto notation = TRY(get_option(global_object, *options, vm.names.notation, Value::Type::String, { "standard"sv, "scientific"sv, "engineering"sv, "compact"sv }, "standard"sv));
  379. // 19. Set numberFormat.[[Notation]] to notation.
  380. number_format.set_notation(notation.as_string().string());
  381. // 20. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation).
  382. TRY(set_number_format_digit_options(global_object, number_format, *options, default_min_fraction_digits, default_max_fraction_digits, number_format.notation()));
  383. // 21. Let compactDisplay be ? GetOption(options, "compactDisplay", "string", « "short", "long" », "short").
  384. auto compact_display = TRY(get_option(global_object, *options, vm.names.compactDisplay, Value::Type::String, { "short"sv, "long"sv }, "short"sv));
  385. // 22. If notation is "compact", then
  386. if (number_format.notation() == NumberFormat::Notation::Compact) {
  387. // a. Set numberFormat.[[CompactDisplay]] to compactDisplay.
  388. number_format.set_compact_display(compact_display.as_string().string());
  389. }
  390. // 23. Let useGrouping be ? GetOption(options, "useGrouping", "boolean", undefined, true).
  391. auto use_grouping = TRY(get_option(global_object, *options, vm.names.useGrouping, Value::Type::Boolean, {}, true));
  392. // 24. Set numberFormat.[[UseGrouping]] to useGrouping.
  393. number_format.set_use_grouping(use_grouping.as_bool());
  394. // 25. Let signDisplay be ? GetOption(options, "signDisplay", "string", « "auto", "never", "always", "exceptZero" », "auto").
  395. auto sign_display = TRY(get_option(global_object, *options, vm.names.signDisplay, Value::Type::String, { "auto"sv, "never"sv, "always"sv, "exceptZero"sv }, "auto"sv));
  396. // 26. Set numberFormat.[[SignDisplay]] to signDisplay.
  397. number_format.set_sign_display(sign_display.as_string().string());
  398. // 27. Return numberFormat.
  399. return &number_format;
  400. }
  401. // 15.1.3 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  402. int currency_digits(StringView currency)
  403. {
  404. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  405. // unit value corresponding to the currency from the list; otherwise, return 2.
  406. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  407. return currency_code->minor_unit.value_or(2);
  408. return 2;
  409. }
  410. // 15.1.5 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  411. FormatResult format_numeric_to_string(NumberFormat& number_format, double number)
  412. {
  413. // 1. If x < 0 or x is -0𝔽, let isNegative be true; else let isNegative be false.
  414. bool is_negative = (number < 0.0) || Value(number).is_negative_zero();
  415. // 2. If isNegative, then
  416. if (is_negative) {
  417. // a. Let x be -x.
  418. number *= -1;
  419. }
  420. RawFormatResult result {};
  421. switch (number_format.rounding_type()) {
  422. // 3. If intlObject.[[RoundingType]] is significantDigits, then
  423. case NumberFormat::RoundingType::SignificantDigits:
  424. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]]).
  425. result = to_raw_precision(number, number_format.min_significant_digits(), number_format.max_significant_digits());
  426. break;
  427. // 4. Else if intlObject.[[RoundingType]] is fractionDigits, then
  428. case NumberFormat::RoundingType::FractionDigits:
  429. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]]).
  430. result = to_raw_fixed(number, number_format.min_fraction_digits(), number_format.max_fraction_digits());
  431. break;
  432. // 5. Else,
  433. case NumberFormat::RoundingType::CompactRounding:
  434. // a. Assert: intlObject.[[RoundingType]] is compactRounding.
  435. // b. Let result be ToRawPrecision(x, 1, 2).
  436. result = to_raw_precision(number, 1, 2);
  437. // c. If result.[[IntegerDigitsCount]] > 1, then
  438. if (result.digits > 1) {
  439. // i. Let result be ToRawFixed(x, 0, 0).
  440. result = to_raw_fixed(number, 0, 0);
  441. }
  442. break;
  443. default:
  444. VERIFY_NOT_REACHED();
  445. }
  446. // 6. Let x be result.[[RoundedNumber]].
  447. number = result.rounded_number;
  448. // 7. Let string be result.[[FormattedString]].
  449. auto string = move(result.formatted_string);
  450. // 8. Let int be result.[[IntegerDigitsCount]].
  451. int digits = result.digits;
  452. // 9. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  453. int min_integer = number_format.min_integer_digits();
  454. // 10. If int < minInteger, then
  455. if (digits < min_integer) {
  456. // a. Let forwardZeros be the String consisting of minInteger–int occurrences of the character "0".
  457. auto forward_zeros = String::repeated('0', min_integer - digits);
  458. // b. Set string to the string-concatenation of forwardZeros and string.
  459. string = String::formatted("{}{}", forward_zeros, string);
  460. }
  461. // 11. If isNegative, then
  462. if (is_negative) {
  463. // a. Let x be -x.
  464. number *= -1;
  465. }
  466. // 12. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  467. return { move(string), number };
  468. }
  469. // 15.1.6 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  470. Vector<PatternPartition> partition_number_pattern(NumberFormat& number_format, double number)
  471. {
  472. // 1. Let exponent be 0.
  473. int exponent = 0;
  474. String formatted_string;
  475. // 2. If x is NaN, then
  476. if (Value(number).is_nan()) {
  477. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  478. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::NaN).value_or("NaN"sv);
  479. }
  480. // 3. Else if x is +∞, then
  481. else if (Value(number).is_positive_infinity()) {
  482. // a. Let n be an ILD String value indicating positive infinity.
  483. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Infinity).value_or("infinity"sv);
  484. }
  485. // 4. Else if x is -∞, then
  486. else if (Value(number).is_negative_infinity()) {
  487. // a. Let n be an ILD String value indicating negative infinity.
  488. // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
  489. // be inserted by the pattern returned from GetNumberFormatPattern.
  490. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Infinity).value_or("infinity"sv);
  491. }
  492. // 5. Else,
  493. else {
  494. // a. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  495. if (number_format.style() == NumberFormat::Style::Percent)
  496. number = number * 100;
  497. // b. Let exponent be ComputeExponent(numberFormat, x).
  498. exponent = compute_exponent(number_format, number);
  499. // c. Let x be x × 10^(-exponent).
  500. number *= pow(10, -exponent);
  501. // d. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  502. auto format_number_result = format_numeric_to_string(number_format, number);
  503. // e. Let n be formatNumberResult.[[FormattedString]].
  504. formatted_string = move(format_number_result.formatted_string);
  505. // f. Let x be formatNumberResult.[[RoundedNumber]].
  506. number = format_number_result.rounded_number;
  507. }
  508. Unicode::NumberFormat found_pattern {};
  509. // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
  510. auto pattern = get_number_format_pattern(number_format, number, found_pattern);
  511. if (!pattern.has_value())
  512. return {};
  513. // 7. Let result be a new empty List.
  514. Vector<PatternPartition> result;
  515. // 8. Let patternParts be PartitionPattern(pattern).
  516. auto pattern_parts = pattern->visit([](auto const& p) { return partition_pattern(p); });
  517. // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  518. for (auto& pattern_part : pattern_parts) {
  519. // a. Let p be patternPart.[[Type]].
  520. auto part = pattern_part.type;
  521. // b. If p is "literal", then
  522. if (part == "literal"sv) {
  523. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  524. result.append({ "literal"sv, move(pattern_part.value) });
  525. }
  526. // c. Else if p is equal to "number", then
  527. else if (part == "number"sv) {
  528. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  529. auto notation_sub_parts = partition_notation_sub_pattern(number_format, number, formatted_string, exponent);
  530. // ii. Append all elements of notationSubParts to result.
  531. result.extend(move(notation_sub_parts));
  532. }
  533. // d. Else if p is equal to "plusSign", then
  534. else if (part == "plusSign"sv) {
  535. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  536. auto plus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::PlusSign).value_or("+"sv);
  537. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  538. result.append({ "plusSign"sv, plus_sign_symbol });
  539. }
  540. // e. Else if p is equal to "minusSign", then
  541. else if (part == "minusSign"sv) {
  542. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  543. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::MinusSign).value_or("-"sv);
  544. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  545. result.append({ "minusSign"sv, minus_sign_symbol });
  546. }
  547. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  548. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  549. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  550. auto percent_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::PercentSign).value_or("%"sv);
  551. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  552. result.append({ "percentSign"sv, percent_sign_symbol });
  553. }
  554. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  555. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  556. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  557. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  558. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  559. VERIFY(identifier_index.has_value());
  560. // i. Let unit be numberFormat.[[Unit]].
  561. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  562. // iii. Let mu be an ILD String value representing unit before x in unitDisplay form, which may depend on x in languages having different plural forms.
  563. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  564. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  565. result.append({ "unit"sv, unit_identifier });
  566. }
  567. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  568. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  569. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  570. //
  571. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  572. // currency code during GetNumberFormatPattern so that we do not have to do currency
  573. // display / plurality lookups more than once.
  574. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  575. result.append({ "currency"sv, number_format.resolve_currency_display() });
  576. }
  577. // l. Else,
  578. else {
  579. // i. Let unknown be an ILND String based on x and p.
  580. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  581. // LibUnicode doesn't generate any "unknown" patterns.
  582. VERIFY_NOT_REACHED();
  583. }
  584. }
  585. // 10. Return result.
  586. return result;
  587. }
  588. static Vector<StringView> separate_integer_into_groups(Unicode::NumberGroupings const& grouping_sizes, StringView integer)
  589. {
  590. Utf8View utf8_integer { integer };
  591. if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
  592. return { integer };
  593. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  594. if (index < grouping_sizes.minimum_grouping_digits)
  595. return { integer };
  596. Vector<StringView> groups;
  597. auto add_group = [&](size_t index, size_t length) {
  598. groups.prepend(utf8_integer.unicode_substring_view(index, length).as_string());
  599. };
  600. add_group(index, grouping_sizes.primary_grouping_size);
  601. while (index > grouping_sizes.secondary_grouping_size) {
  602. index -= grouping_sizes.secondary_grouping_size;
  603. add_group(index, grouping_sizes.secondary_grouping_size);
  604. }
  605. if (index > 0)
  606. add_group(0, index);
  607. return groups;
  608. }
  609. // 15.1.7 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  610. Vector<PatternPartition> partition_notation_sub_pattern(NumberFormat& number_format, double number, String formatted_string, int exponent)
  611. {
  612. // 1. Let result be a new empty List.
  613. Vector<PatternPartition> result;
  614. auto grouping_sizes = Unicode::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  615. if (!grouping_sizes.has_value())
  616. return {};
  617. // 2. If x is NaN, then
  618. if (Value(number).is_nan()) {
  619. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  620. result.append({ "nan"sv, move(formatted_string) });
  621. }
  622. // 3. Else if x is a non-finite Number, then
  623. else if (!Value(number).is_finite_number()) {
  624. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  625. result.append({ "infinity"sv, move(formatted_string) });
  626. }
  627. // 4. Else,
  628. else {
  629. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  630. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  631. if (!notation_sub_pattern.has_value())
  632. return {};
  633. // b. Let patternParts be PartitionPattern(notationSubPattern).
  634. auto pattern_parts = partition_pattern(*notation_sub_pattern);
  635. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  636. for (auto& pattern_part : pattern_parts) {
  637. // i. Let p be patternPart.[[Type]].
  638. auto part = pattern_part.type;
  639. // ii. If p is "literal", then
  640. if (part == "literal"sv) {
  641. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  642. result.append({ "literal"sv, move(pattern_part.value) });
  643. }
  644. // iii. Else if p is equal to "number", then
  645. else if (part == "number"sv) {
  646. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 10 below, then
  647. // a. Let digits be a List whose 10 String valued elements are the UTF-16 string representations of the 10 digits specified in the "Digits" column of the matching row in Table 10.
  648. // b. Replace each digit in n with the value of digits[digit].
  649. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  650. formatted_string = Unicode::replace_digits_for_number_system(number_format.numbering_system(), formatted_string);
  651. // 3. Let decimalSepIndex be ! StringIndexOf(n, ".", 0).
  652. auto decimal_sep_index = formatted_string.find('.');
  653. StringView integer;
  654. Optional<StringView> fraction;
  655. // 4. If decimalSepIndex > 0, then
  656. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  657. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  658. integer = formatted_string.substring_view(0, *decimal_sep_index);
  659. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  660. fraction = formatted_string.substring_view(*decimal_sep_index + 1);
  661. }
  662. // 5. Else,
  663. else {
  664. // a. Let integer be n.
  665. integer = formatted_string;
  666. // b. Let fraction be undefined.
  667. }
  668. bool use_grouping = number_format.use_grouping();
  669. // FIXME: The spec doesn't indicate this, but grouping should be disabled for numbers less than 10,000 when the notation is compact.
  670. // This is addressed in Intl.NumberFormat V3 with the "min2" [[UseGrouping]] option. However, test262 explicitly expects this
  671. // behavior in the "de-DE" locale tests, because this is how ICU (and therefore V8, SpiderMoney, etc.) has always behaved.
  672. //
  673. // So, in locales "de-*", we must have:
  674. // Intl.NumberFormat("de", {notation: "compact"}).format(1234) === "1234"
  675. // Intl.NumberFormat("de", {notation: "compact"}).format(12345) === "12.345"
  676. // Intl.NumberFormat("de").format(1234) === "1.234"
  677. // Intl.NumberFormat("de").format(12345) === "12.345"
  678. //
  679. // See: https://github.com/tc39/proposal-intl-numberformat-v3/issues/3
  680. if (number_format.has_compact_format())
  681. use_grouping = number >= 10'000;
  682. // 6. If the numberFormat.[[UseGrouping]] is true, then
  683. if (use_grouping) {
  684. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  685. auto group_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Group).value_or(","sv);
  686. // b. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer.
  687. auto groups = separate_integer_into_groups(*grouping_sizes, integer);
  688. // c. Assert: The number of elements in groups List is greater than 0.
  689. VERIFY(!groups.is_empty());
  690. // d. Repeat, while groups List is not empty,
  691. while (!groups.is_empty()) {
  692. // i. Remove the first element from groups and let integerGroup be the value of that element.
  693. auto integer_group = groups.take_first();
  694. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  695. result.append({ "integer"sv, integer_group });
  696. // iii. If groups List is not empty, then
  697. if (!groups.is_empty()) {
  698. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  699. result.append({ "group"sv, group_sep_symbol });
  700. }
  701. }
  702. }
  703. // 7. Else,
  704. else {
  705. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  706. result.append({ "integer"sv, integer });
  707. }
  708. // 8. If fraction is not undefined, then
  709. if (fraction.has_value()) {
  710. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  711. auto decimal_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Decimal).value_or("."sv);
  712. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  713. result.append({ "decimal"sv, decimal_sep_symbol });
  714. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  715. result.append({ "fraction"sv, fraction.release_value() });
  716. }
  717. }
  718. // iv. Else if p is equal to "compactSymbol", then
  719. // v. Else if p is equal to "compactName", then
  720. else if (part.starts_with("compactIdentifier:"sv)) {
  721. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  722. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  723. VERIFY(identifier_index.has_value());
  724. // 1. Let compactSymbol be an ILD string representing exponent in short form, which may depend on x in languages having different plural forms. The implementation must be able to provide this string, or else the pattern would not have a "{compactSymbol}" placeholder.
  725. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  726. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  727. result.append({ "compact"sv, compact_identifier });
  728. }
  729. // vi. Else if p is equal to "scientificSeparator", then
  730. else if (part == "scientificSeparator"sv) {
  731. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  732. auto scientific_separator = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Exponential).value_or("E"sv);
  733. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  734. result.append({ "exponentSeparator"sv, scientific_separator });
  735. }
  736. // vii. Else if p is equal to "scientificExponent", then
  737. else if (part == "scientificExponent"sv) {
  738. // 1. If exponent < 0, then
  739. if (exponent < 0) {
  740. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  741. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::MinusSign).value_or("-"sv);
  742. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  743. result.append({ "exponentMinusSign"sv, minus_sign_symbol });
  744. // c. Let exponent be -exponent.
  745. exponent *= -1;
  746. }
  747. // 2. Let exponentResult be ToRawFixed(exponent, 1, 0, 0).
  748. // Note: See the implementation of ToRawFixed for why we do not pass the 1.
  749. auto exponent_result = to_raw_fixed(exponent, 0, 0);
  750. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  751. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  752. exponent_result.formatted_string = Unicode::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string);
  753. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  754. result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
  755. }
  756. // viii. Else,
  757. else {
  758. // 1. Let unknown be an ILND String based on x and p.
  759. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  760. // LibUnicode doesn't generate any "unknown" patterns.
  761. VERIFY_NOT_REACHED();
  762. }
  763. }
  764. }
  765. // 5. Return result.
  766. return result;
  767. }
  768. // 15.1.8 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  769. String format_numeric(NumberFormat& number_format, double number)
  770. {
  771. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  772. // Note: Our implementation of PartitionNumberPattern does not throw.
  773. auto parts = partition_number_pattern(number_format, number);
  774. // 2. Let result be the empty String.
  775. StringBuilder result;
  776. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  777. for (auto& part : parts) {
  778. // a. Set result to the string-concatenation of result and part.[[Value]].
  779. result.append(move(part.value));
  780. }
  781. // 4. Return result.
  782. return result.build();
  783. }
  784. // 15.1.9 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  785. Array* format_numeric_to_parts(GlobalObject& global_object, NumberFormat& number_format, double number)
  786. {
  787. auto& vm = global_object.vm();
  788. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  789. // Note: Our implementation of PartitionNumberPattern does not throw.
  790. auto parts = partition_number_pattern(number_format, number);
  791. // 2. Let result be ArrayCreate(0).
  792. auto* result = MUST(Array::create(global_object, 0));
  793. // 3. Let n be 0.
  794. size_t n = 0;
  795. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  796. for (auto& part : parts) {
  797. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  798. auto* object = Object::create(global_object, global_object.object_prototype());
  799. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  800. MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
  801. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  802. MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
  803. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  804. MUST(result->create_data_property_or_throw(n, object));
  805. // e. Increment n by 1.
  806. ++n;
  807. }
  808. // 5. Return result.
  809. return result;
  810. }
  811. static String cut_trailing_zeroes(StringView string, int cut)
  812. {
  813. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  814. // Repeat, while cut > 0 and the last character of m is "0",
  815. while ((cut > 0) && string.ends_with('0')) {
  816. // Remove the last character from m.
  817. string = string.substring_view(0, string.length() - 1);
  818. // Decrease cut by 1.
  819. --cut;
  820. }
  821. // If the last character of m is ".", then
  822. if (string.ends_with('.')) {
  823. // Remove the last character from m.
  824. string = string.substring_view(0, string.length() - 1);
  825. }
  826. return string.to_string();
  827. }
  828. // 15.1.10 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  829. RawFormatResult to_raw_precision(double number, int min_precision, int max_precision)
  830. {
  831. RawFormatResult result {};
  832. // 1. Set x to ℝ(x).
  833. // FIXME: Support BigInt number formatting.
  834. // 2. Let p be maxPrecision.
  835. int precision = max_precision;
  836. int exponent = 0;
  837. // 3. If x = 0, then
  838. if (number == 0.0) {
  839. // a. Let m be the String consisting of p occurrences of the character "0".
  840. result.formatted_string = String::repeated('0', precision);
  841. // b. Let e be 0.
  842. exponent = 0;
  843. // c. Let xFinal be 0.
  844. result.rounded_number = 0;
  845. }
  846. // 4. Else,
  847. else {
  848. // FIXME: The result of these steps isn't entirely accurate for large values of 'p' (which
  849. // defaults to 21, resulting in numbers on the order of 10^21). Either AK::format or
  850. // our Number::toString AO (double_to_string in Value.cpp) will need to be improved
  851. // to produce more accurate results.
  852. // a. Let e and n be integers such that 10^(p–1) ≤ n < 10^p and for which n × 10^(e–p+1) – x is as close to zero as possible.
  853. // If there are two such sets of e and n, pick the e and n for which n × 10^(e–p+1) is larger.
  854. exponent = log10floor(number);
  855. double power = pow(10, exponent - precision + 1);
  856. double n = round(number / power);
  857. // b. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  858. result.formatted_string = Value(n).to_string_without_side_effects();
  859. // c. Let xFinal be n × 10^(e–p+1).
  860. result.rounded_number = n * power;
  861. }
  862. // 5. If e ≥ p–1, then
  863. if (exponent >= (precision - 1)) {
  864. // a. Let m be the string-concatenation of m and e–p+1 occurrences of the character "0".
  865. result.formatted_string = String::formatted(
  866. "{}{}",
  867. result.formatted_string,
  868. String::repeated('0', exponent - precision + 1));
  869. // b. Let int be e+1.
  870. result.digits = exponent + 1;
  871. }
  872. // 6. Else if e ≥ 0, then
  873. else if (exponent >= 0) {
  874. // a. Let m be the string-concatenation of the first e+1 characters of m, the character ".", and the remaining p–(e+1) characters of m.
  875. result.formatted_string = String::formatted(
  876. "{}.{}",
  877. result.formatted_string.substring_view(0, exponent + 1),
  878. result.formatted_string.substring_view(exponent + 1));
  879. // b. Let int be e+1.
  880. result.digits = exponent + 1;
  881. }
  882. // 7. Else,
  883. else {
  884. // a. Assert: e < 0.
  885. // b. Let m be the string-concatenation of the String value "0.", –(e+1) occurrences of the character "0", and m.
  886. result.formatted_string = String::formatted(
  887. "0.{}{}",
  888. String::repeated('0', -1 * (exponent + 1)),
  889. result.formatted_string);
  890. // c. Let int be 1.
  891. result.digits = 1;
  892. }
  893. // 8. If m contains the character ".", and maxPrecision > minPrecision, then
  894. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  895. // a. Let cut be maxPrecision – minPrecision.
  896. int cut = max_precision - min_precision;
  897. // Steps 8b-8c are implemented by cut_trailing_zeroes.
  898. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  899. }
  900. // 9. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  901. return result;
  902. }
  903. // 15.1.11 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  904. // NOTE: The spec has a mistake here. The minInteger parameter is unused and is not provided by FormatNumericToString.
  905. RawFormatResult to_raw_fixed(double number, int min_fraction, int max_fraction)
  906. {
  907. RawFormatResult result {};
  908. // 1. Set x to ℝ(x).
  909. // FIXME: Support BigInt number formatting.
  910. // 2. Let f be maxFraction.
  911. int fraction = max_fraction;
  912. double power = pow(10, fraction);
  913. // 3. Let n be an integer for which the exact mathematical value of n / 10^f – x is as close to zero as possible. If there are two such n, pick the larger n.
  914. double n = round(number * power);
  915. // 4. Let xFinal be n / 10^f.
  916. result.rounded_number = n / power;
  917. // 5. If n = 0, let m be the String "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  918. result.formatted_string = n == 0.0 ? String("0"sv) : Value(n).to_string_without_side_effects();
  919. // 6. If f ≠ 0, then
  920. if (fraction != 0) {
  921. // a. Let k be the number of characters in m.
  922. auto decimals = result.formatted_string.length();
  923. // b. If k ≤ f, then
  924. if (decimals <= static_cast<size_t>(fraction)) {
  925. // i. Let z be the String value consisting of f+1–k occurrences of the character "0".
  926. auto zeroes = String::repeated('0', fraction + 1 - decimals);
  927. // ii. Let m be the string-concatenation of z and m.
  928. result.formatted_string = String::formatted("{}{}", zeroes, result.formatted_string);
  929. // iii. Let k be f+1.
  930. decimals = fraction + 1;
  931. }
  932. // c. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
  933. auto a = result.formatted_string.substring_view(0, decimals - fraction);
  934. auto b = result.formatted_string.substring_view(decimals - fraction, fraction);
  935. // d. Let m be the string-concatenation of a, ".", and b.
  936. result.formatted_string = String::formatted("{}.{}", a, b);
  937. // e. Let int be the number of characters in a.
  938. result.digits = a.length();
  939. }
  940. // 7. Else, let int be the number of characters in m.
  941. else {
  942. result.digits = result.formatted_string.length();
  943. }
  944. // 8. Let cut be maxFraction – minFraction.
  945. int cut = max_fraction - min_fraction;
  946. // Steps 9-10 are implemented by cut_trailing_zeroes.
  947. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  948. // 11. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  949. return result;
  950. }
  951. // 15.1.13 SetNumberFormatUnitOptions ( intlObj, options ), https://tc39.es/ecma402/#sec-setnumberformatunitoptions
  952. ThrowCompletionOr<void> set_number_format_unit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options)
  953. {
  954. auto& vm = global_object.vm();
  955. // 1. Assert: Type(intlObj) is Object.
  956. // 2. Assert: Type(options) is Object.
  957. // 3. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
  958. auto style = TRY(get_option(global_object, options, vm.names.style, Value::Type::String, { "decimal"sv, "percent"sv, "currency"sv, "unit"sv }, "decimal"sv));
  959. // 4. Set intlObj.[[Style]] to style.
  960. intl_object.set_style(style.as_string().string());
  961. // 5. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
  962. auto currency = TRY(get_option(global_object, options, vm.names.currency, Value::Type::String, {}, Empty {}));
  963. // 6. If currency is undefined, then
  964. if (currency.is_undefined()) {
  965. // a. If style is "currency", throw a TypeError exception.
  966. if (intl_object.style() == NumberFormat::Style::Currency)
  967. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "currency"sv, "style"sv, style);
  968. }
  969. // 7. Else,
  970. // a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
  971. else if (!is_well_formed_currency_code(currency.as_string().string()))
  972. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, currency, "currency"sv);
  973. // 8. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
  974. auto currency_display = TRY(get_option(global_object, options, vm.names.currencyDisplay, Value::Type::String, { "code"sv, "symbol"sv, "narrowSymbol"sv, "name"sv }, "symbol"sv));
  975. // 9. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
  976. auto currency_sign = TRY(get_option(global_object, options, vm.names.currencySign, Value::Type::String, { "standard"sv, "accounting"sv }, "standard"sv));
  977. // 10. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
  978. auto unit = TRY(get_option(global_object, options, vm.names.unit, Value::Type::String, {}, Empty {}));
  979. // 11. If unit is undefined, then
  980. if (unit.is_undefined()) {
  981. // a. If style is "unit", throw a TypeError exception.
  982. if (intl_object.style() == NumberFormat::Style::Unit)
  983. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "unit"sv, "style"sv, style);
  984. }
  985. // 12. Else,
  986. // a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
  987. else if (!is_well_formed_unit_identifier(unit.as_string().string()))
  988. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "unit"sv);
  989. // 13. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
  990. auto unit_display = TRY(get_option(global_object, options, vm.names.unitDisplay, Value::Type::String, { "short"sv, "narrow"sv, "long"sv }, "short"sv));
  991. // 14. If style is "currency", then
  992. if (intl_object.style() == NumberFormat::Style::Currency) {
  993. // a. Let currency be the result of converting currency to upper case as specified in 6.1.
  994. // b. Set intlObj.[[Currency]] to currency.
  995. intl_object.set_currency(currency.as_string().string().to_uppercase());
  996. // c. Set intlObj.[[CurrencyDisplay]] to currencyDisplay.
  997. intl_object.set_currency_display(currency_display.as_string().string());
  998. // d. Set intlObj.[[CurrencySign]] to currencySign.
  999. intl_object.set_currency_sign(currency_sign.as_string().string());
  1000. }
  1001. // 15. If style is "unit", then
  1002. if (intl_object.style() == NumberFormat::Style::Unit) {
  1003. // a. Set intlObj.[[Unit]] to unit.
  1004. intl_object.set_unit(unit.as_string().string());
  1005. // b. Set intlObj.[[UnitDisplay]] to unitDisplay.
  1006. intl_object.set_unit_display(unit_display.as_string().string());
  1007. }
  1008. return {};
  1009. }
  1010. // 15.1.14 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  1011. Optional<Variant<StringView, String>> get_number_format_pattern(NumberFormat& number_format, double number, Unicode::NumberFormat& found_pattern)
  1012. {
  1013. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1014. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1015. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1016. // 4. Let patterns be dataLocaleData.[[patterns]].
  1017. // 5. Assert: patterns is a Record (see 15.3.3).
  1018. Optional<Unicode::NumberFormat> patterns;
  1019. // 6. Let style be numberFormat.[[Style]].
  1020. switch (number_format.style()) {
  1021. // 7. If style is "percent", then
  1022. case NumberFormat::Style::Percent:
  1023. // a. Let patterns be patterns.[[percent]].
  1024. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Percent);
  1025. break;
  1026. // 8. Else if style is "unit", then
  1027. case NumberFormat::Style::Unit: {
  1028. // a. Let unit be numberFormat.[[Unit]].
  1029. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1030. // c. Let patterns be patterns.[[unit]].
  1031. // d. If patterns doesn't have a field [[<unit>]], then
  1032. // i. Let unit be "fallback".
  1033. // e. Let patterns be patterns.[[<unit>]].
  1034. // f. Let patterns be patterns.[[<unitDisplay>]].
  1035. auto formats = Unicode::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display());
  1036. patterns = Unicode::select_pattern_with_plurality(formats, number);
  1037. break;
  1038. }
  1039. // 9. Else if style is "currency", then
  1040. case NumberFormat::Style::Currency:
  1041. // a. Let currency be numberFormat.[[Currency]].
  1042. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1043. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1044. // d. Let patterns be patterns.[[currency]].
  1045. // e. If patterns doesn't have a field [[<currency>]], then
  1046. // i. Let currency be "fallback".
  1047. // f. Let patterns be patterns.[[<currency>]].
  1048. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1049. // h. Let patterns be patterns.[[<currencySign>]].
  1050. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  1051. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  1052. auto formats = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyUnit);
  1053. auto maybe_patterns = Unicode::select_pattern_with_plurality(formats, number);
  1054. if (maybe_patterns.has_value()) {
  1055. patterns = maybe_patterns.release_value();
  1056. break;
  1057. }
  1058. }
  1059. switch (number_format.currency_sign()) {
  1060. case NumberFormat::CurrencySign::Standard:
  1061. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Currency);
  1062. break;
  1063. case NumberFormat::CurrencySign::Accounting:
  1064. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Accounting);
  1065. break;
  1066. }
  1067. break;
  1068. // 10. Else,
  1069. case NumberFormat::Style::Decimal:
  1070. // a. Assert: style is "decimal".
  1071. // b. Let patterns be patterns.[[decimal]].
  1072. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Decimal);
  1073. break;
  1074. default:
  1075. VERIFY_NOT_REACHED();
  1076. }
  1077. if (!patterns.has_value())
  1078. return {};
  1079. StringView pattern;
  1080. Value number_value(number);
  1081. bool is_positive_zero = number_value.is_positive_zero();
  1082. bool is_negative_zero = number_value.is_negative_zero();
  1083. bool is_nan = number_value.is_nan();
  1084. // 11. Let signDisplay be numberFormat.[[SignDisplay]].
  1085. switch (number_format.sign_display()) {
  1086. // 12. If signDisplay is "never", then
  1087. case NumberFormat::SignDisplay::Never:
  1088. // a. Let pattern be patterns.[[zeroPattern]].
  1089. pattern = patterns->zero_format;
  1090. break;
  1091. // 13. Else if signDisplay is "auto", then
  1092. case NumberFormat::SignDisplay::Auto:
  1093. // a. If x is 0 or x > 0 or x is NaN, then
  1094. if (is_positive_zero || (number > 0) || is_nan) {
  1095. // i. Let pattern be patterns.[[zeroPattern]].
  1096. pattern = patterns->zero_format;
  1097. }
  1098. // b. Else,
  1099. else {
  1100. // i. Let pattern be patterns.[[negativePattern]].
  1101. pattern = patterns->negative_format;
  1102. }
  1103. break;
  1104. // 14. Else if signDisplay is "always", then
  1105. case NumberFormat::SignDisplay::Always:
  1106. // a. If x is 0 or x > 0 or x is NaN, then
  1107. if (is_positive_zero || (number > 0) || is_nan) {
  1108. // i. Let pattern be patterns.[[positivePattern]].
  1109. pattern = patterns->positive_format;
  1110. }
  1111. // b. Else,
  1112. else {
  1113. // i. Let pattern be patterns.[[negativePattern]].
  1114. pattern = patterns->negative_format;
  1115. }
  1116. break;
  1117. // 15. Else,
  1118. case NumberFormat::SignDisplay::ExceptZero:
  1119. // a. Assert: signDisplay is "exceptZero".
  1120. // b. If x is 0 or x is -0 or x is NaN, then
  1121. if (is_positive_zero || is_negative_zero || is_nan) {
  1122. // i. Let pattern be patterns.[[zeroPattern]].
  1123. pattern = patterns->zero_format;
  1124. }
  1125. // c. Else if x > 0, then
  1126. else if (number > 0) {
  1127. // i. Let pattern be patterns.[[positivePattern]].
  1128. pattern = patterns->positive_format;
  1129. }
  1130. // d. Else,
  1131. else {
  1132. // i. Let pattern be patterns.[[negativePattern]].
  1133. pattern = patterns->negative_format;
  1134. }
  1135. break;
  1136. default:
  1137. VERIFY_NOT_REACHED();
  1138. }
  1139. found_pattern = patterns.release_value();
  1140. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  1141. // we might need to mutate the format pattern to inject a space between the currency display and
  1142. // the currency number.
  1143. if (number_format.style() == NumberFormat::Style::Currency) {
  1144. auto modified_pattern = Unicode::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern);
  1145. if (modified_pattern.has_value())
  1146. return modified_pattern.release_value();
  1147. }
  1148. // 16. Return pattern.
  1149. return pattern;
  1150. }
  1151. // 15.1.15 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1152. Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
  1153. {
  1154. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1155. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1156. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1157. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1158. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1159. // 6. Let notation be numberFormat.[[Notation]].
  1160. auto notation = number_format.notation();
  1161. // 7. If notation is "scientific" or notation is "engineering", then
  1162. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1163. // a. Return notationSubPatterns.[[scientific]].
  1164. auto notation_sub_patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Scientific);
  1165. if (!notation_sub_patterns.has_value())
  1166. return {};
  1167. return notation_sub_patterns->zero_format;
  1168. }
  1169. // 8. Else if exponent is not 0, then
  1170. else if (exponent != 0) {
  1171. // a. Assert: notation is "compact".
  1172. VERIFY(notation == NumberFormat::Notation::Compact);
  1173. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1174. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1175. // d. Return compactPatterns.[[<exponent>]].
  1176. if (number_format.has_compact_format())
  1177. return number_format.compact_format().zero_format;
  1178. }
  1179. // 9. Else,
  1180. // a. Return "{number}".
  1181. return "{number}"sv;
  1182. }
  1183. // 15.1.16 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1184. int compute_exponent(NumberFormat& number_format, double number)
  1185. {
  1186. // 1. If x = 0, then
  1187. if (number == 0.0) {
  1188. // a. Return 0.
  1189. return 0;
  1190. }
  1191. // 2. If x < 0, then
  1192. if (number < 0) {
  1193. // a. Let x = -x.
  1194. number *= -1;
  1195. }
  1196. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1197. int magnitude = log10floor(number);
  1198. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1199. int exponent = compute_exponent_for_magnitude(number_format, magnitude);
  1200. // 5. Let x be x × 10^(-exponent).
  1201. number *= pow(10, -exponent);
  1202. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1203. auto format_number_result = format_numeric_to_string(number_format, number);
  1204. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1205. if (format_number_result.rounded_number == 0) {
  1206. // a. Return exponent.
  1207. return exponent;
  1208. }
  1209. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1210. int new_magnitude = log10floor(format_number_result.rounded_number);
  1211. // 9. If newMagnitude is magnitude – exponent, then
  1212. if (new_magnitude == magnitude - exponent) {
  1213. // a. Return exponent.
  1214. return exponent;
  1215. }
  1216. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1217. return compute_exponent_for_magnitude(number_format, magnitude + 1);
  1218. }
  1219. // 15.1.17 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1220. int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
  1221. {
  1222. // 1. Let notation be numberFormat.[[Notation]].
  1223. switch (number_format.notation()) {
  1224. // 2. If notation is "standard", then
  1225. case NumberFormat::Notation::Standard:
  1226. // a. Return 0.
  1227. return 0;
  1228. // 3. Else if notation is "scientific", then
  1229. case NumberFormat::Notation::Scientific:
  1230. // a. Return magnitude.
  1231. return magnitude;
  1232. // 4. Else if notation is "engineering", then
  1233. case NumberFormat::Notation::Engineering: {
  1234. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1235. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1236. // b. Return thousands × 3.
  1237. return static_cast<int>(thousands) * 3;
  1238. }
  1239. // 5. Else,
  1240. case NumberFormat::Notation::Compact: {
  1241. // a. Assert: notation is "compact".
  1242. VERIFY(number_format.has_compact_display());
  1243. // b. Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a number of the given magnitude in compact notation for the current locale.
  1244. // c. Return exponent.
  1245. Vector<Unicode::NumberFormat> format_rules;
  1246. if (number_format.style() == NumberFormat::Style::Currency)
  1247. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyShort);
  1248. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1249. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalLong);
  1250. else
  1251. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalShort);
  1252. Unicode::NumberFormat const* best_number_format = nullptr;
  1253. for (auto const& format_rule : format_rules) {
  1254. if (format_rule.magnitude > magnitude)
  1255. break;
  1256. best_number_format = &format_rule;
  1257. }
  1258. if (best_number_format == nullptr)
  1259. return 0;
  1260. number_format.set_compact_format(*best_number_format);
  1261. return best_number_format->exponent;
  1262. }
  1263. default:
  1264. VERIFY_NOT_REACHED();
  1265. }
  1266. }
  1267. }