NumberFormat.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/Utf8View.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 <LibUnicode/Locale.h>
  13. #include <math.h>
  14. #include <stdlib.h>
  15. namespace JS::Intl {
  16. Vector<StringView> const& NumberFormat::relevant_extension_keys()
  17. {
  18. // 15.3.3 Internal slots, https://tc39.es/ecma402/#sec-intl.numberformat-internal-slots
  19. // The value of the [[RelevantExtensionKeys]] internal slot is « "nu" ».
  20. static Vector<StringView> relevant_extension_keys { "nu"sv };
  21. return relevant_extension_keys;
  22. }
  23. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  24. NumberFormat::NumberFormat(Object& prototype)
  25. : Object(prototype)
  26. {
  27. }
  28. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  29. {
  30. Base::visit_edges(visitor);
  31. if (m_bound_format)
  32. visitor.visit(m_bound_format);
  33. }
  34. void NumberFormat::set_style(StringView style)
  35. {
  36. if (style == "decimal"sv)
  37. m_style = Style::Decimal;
  38. else if (style == "percent"sv)
  39. m_style = Style::Percent;
  40. else if (style == "currency"sv)
  41. m_style = Style::Currency;
  42. else if (style == "unit"sv)
  43. m_style = Style::Unit;
  44. else
  45. VERIFY_NOT_REACHED();
  46. }
  47. StringView NumberFormat::style_string() const
  48. {
  49. switch (m_style) {
  50. case Style::Decimal:
  51. return "decimal"sv;
  52. case Style::Percent:
  53. return "percent"sv;
  54. case Style::Currency:
  55. return "currency"sv;
  56. case Style::Unit:
  57. return "unit"sv;
  58. default:
  59. VERIFY_NOT_REACHED();
  60. }
  61. }
  62. void NumberFormat::set_currency_display(StringView currency_display)
  63. {
  64. if (currency_display == "code"sv)
  65. m_currency_display = CurrencyDisplay::Code;
  66. else if (currency_display == "symbol"sv)
  67. m_currency_display = CurrencyDisplay::Symbol;
  68. else if (currency_display == "narrowSymbol"sv)
  69. m_currency_display = CurrencyDisplay::NarrowSymbol;
  70. else if (currency_display == "name"sv)
  71. m_currency_display = CurrencyDisplay::Name;
  72. else
  73. VERIFY_NOT_REACHED();
  74. }
  75. StringView NumberFormat::currency_display_string() const
  76. {
  77. VERIFY(m_currency_display.has_value());
  78. switch (*m_currency_display) {
  79. case CurrencyDisplay::Code:
  80. return "code"sv;
  81. case CurrencyDisplay::Symbol:
  82. return "symbol"sv;
  83. case CurrencyDisplay::NarrowSymbol:
  84. return "narrowSymbol"sv;
  85. case CurrencyDisplay::Name:
  86. return "name"sv;
  87. default:
  88. VERIFY_NOT_REACHED();
  89. }
  90. }
  91. void NumberFormat::set_currency_sign(StringView currency_sign)
  92. {
  93. if (currency_sign == "standard"sv)
  94. m_currency_sign = CurrencySign::Standard;
  95. else if (currency_sign == "accounting"sv)
  96. m_currency_sign = CurrencySign::Accounting;
  97. else
  98. VERIFY_NOT_REACHED();
  99. }
  100. StringView NumberFormat::currency_sign_string() const
  101. {
  102. VERIFY(m_currency_sign.has_value());
  103. switch (*m_currency_sign) {
  104. case CurrencySign::Standard:
  105. return "standard"sv;
  106. case CurrencySign::Accounting:
  107. return "accounting"sv;
  108. default:
  109. VERIFY_NOT_REACHED();
  110. }
  111. }
  112. void NumberFormat::set_unit_display(StringView unit_display)
  113. {
  114. if (unit_display == "short"sv)
  115. m_unit_display = UnitDisplay::Short;
  116. else if (unit_display == "narrow"sv)
  117. m_unit_display = UnitDisplay::Narrow;
  118. else if (unit_display == "long"sv)
  119. m_unit_display = UnitDisplay::Long;
  120. else
  121. VERIFY_NOT_REACHED();
  122. }
  123. StringView NumberFormat::unit_display_string() const
  124. {
  125. VERIFY(m_unit_display.has_value());
  126. switch (*m_unit_display) {
  127. case UnitDisplay::Short:
  128. return "short"sv;
  129. case UnitDisplay::Narrow:
  130. return "narrow"sv;
  131. case UnitDisplay::Long:
  132. return "long"sv;
  133. default:
  134. VERIFY_NOT_REACHED();
  135. }
  136. }
  137. StringView NumberFormat::rounding_type_string() const
  138. {
  139. switch (m_rounding_type) {
  140. case RoundingType::SignificantDigits:
  141. return "significantDigits"sv;
  142. case RoundingType::FractionDigits:
  143. return "fractionDigits"sv;
  144. case RoundingType::CompactRounding:
  145. return "compactRounding"sv;
  146. default:
  147. VERIFY_NOT_REACHED();
  148. }
  149. }
  150. void NumberFormat::set_notation(StringView notation)
  151. {
  152. if (notation == "standard"sv)
  153. m_notation = Notation::Standard;
  154. else if (notation == "scientific"sv)
  155. m_notation = Notation::Scientific;
  156. else if (notation == "engineering"sv)
  157. m_notation = Notation::Engineering;
  158. else if (notation == "compact"sv)
  159. m_notation = Notation::Compact;
  160. else
  161. VERIFY_NOT_REACHED();
  162. }
  163. StringView NumberFormat::notation_string() const
  164. {
  165. switch (m_notation) {
  166. case Notation::Standard:
  167. return "standard"sv;
  168. case Notation::Scientific:
  169. return "scientific"sv;
  170. case Notation::Engineering:
  171. return "engineering"sv;
  172. case Notation::Compact:
  173. return "compact"sv;
  174. default:
  175. VERIFY_NOT_REACHED();
  176. }
  177. }
  178. void NumberFormat::set_compact_display(StringView compact_display)
  179. {
  180. if (compact_display == "short"sv)
  181. m_compact_display = CompactDisplay::Short;
  182. else if (compact_display == "long"sv)
  183. m_compact_display = CompactDisplay::Long;
  184. else
  185. VERIFY_NOT_REACHED();
  186. }
  187. StringView NumberFormat::compact_display_string() const
  188. {
  189. VERIFY(m_compact_display.has_value());
  190. switch (*m_compact_display) {
  191. case CompactDisplay::Short:
  192. return "short"sv;
  193. case CompactDisplay::Long:
  194. return "long"sv;
  195. default:
  196. VERIFY_NOT_REACHED();
  197. }
  198. }
  199. void NumberFormat::set_sign_display(StringView sign_display)
  200. {
  201. if (sign_display == "auto"sv)
  202. m_sign_display = SignDisplay::Auto;
  203. else if (sign_display == "never"sv)
  204. m_sign_display = SignDisplay::Never;
  205. else if (sign_display == "always"sv)
  206. m_sign_display = SignDisplay::Always;
  207. else if (sign_display == "exceptZero"sv)
  208. m_sign_display = SignDisplay::ExceptZero;
  209. else
  210. VERIFY_NOT_REACHED();
  211. }
  212. StringView NumberFormat::sign_display_string() const
  213. {
  214. switch (m_sign_display) {
  215. case SignDisplay::Auto:
  216. return "auto"sv;
  217. case SignDisplay::Never:
  218. return "never"sv;
  219. case SignDisplay::Always:
  220. return "always"sv;
  221. case SignDisplay::ExceptZero:
  222. return "exceptZero"sv;
  223. default:
  224. VERIFY_NOT_REACHED();
  225. }
  226. }
  227. static ALWAYS_INLINE int log10floor(double value)
  228. {
  229. return static_cast<int>(floor(log10(value)));
  230. }
  231. // 15.1.1 SetNumberFormatDigitOptions ( intlObj, options, mnfdDefault, mxfdDefault, notation ), https://tc39.es/ecma402/#sec-setnfdigitoptions
  232. 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)
  233. {
  234. auto& vm = global_object.vm();
  235. // 1. Assert: Type(intlObj) is Object.
  236. // 2. Assert: Type(options) is Object.
  237. // 3. Assert: Type(mnfdDefault) is Number.
  238. // 4. Assert: Type(mxfdDefault) is Number.
  239. // 5. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1).
  240. auto min_integer_digits = TRY(get_number_option(global_object, options, vm.names.minimumIntegerDigits, 1, 21, 1));
  241. // 6. Let mnfd be ? Get(options, "minimumFractionDigits").
  242. auto min_fraction_digits = TRY(options.get(vm.names.minimumFractionDigits));
  243. // 7. Let mxfd be ? Get(options, "maximumFractionDigits").
  244. auto max_fraction_digits = TRY(options.get(vm.names.maximumFractionDigits));
  245. // 8. Let mnsd be ? Get(options, "minimumSignificantDigits").
  246. auto min_significant_digits = TRY(options.get(vm.names.minimumSignificantDigits));
  247. // 9. Let mxsd be ? Get(options, "maximumSignificantDigits").
  248. auto max_significant_digits = TRY(options.get(vm.names.maximumSignificantDigits));
  249. // 10. Set intlObj.[[MinimumIntegerDigits]] to mnid.
  250. intl_object.set_min_integer_digits(*min_integer_digits);
  251. // 11. If mnsd is not undefined or mxsd is not undefined, then
  252. if (!min_significant_digits.is_undefined() || !max_significant_digits.is_undefined()) {
  253. // a. Set intlObj.[[RoundingType]] to significantDigits.
  254. intl_object.set_rounding_type(NumberFormat::RoundingType::SignificantDigits);
  255. // b. Let mnsd be ? DefaultNumberOption(mnsd, 1, 21, 1).
  256. auto min_digits = TRY(default_number_option(global_object, min_significant_digits, 1, 21, 1));
  257. // c. Let mxsd be ? DefaultNumberOption(mxsd, mnsd, 21, 21).
  258. auto max_digits = TRY(default_number_option(global_object, max_significant_digits, *min_digits, 21, 21));
  259. // d. Set intlObj.[[MinimumSignificantDigits]] to mnsd.
  260. intl_object.set_min_significant_digits(*min_digits);
  261. // e. Set intlObj.[[MaximumSignificantDigits]] to mxsd.
  262. intl_object.set_max_significant_digits(*max_digits);
  263. }
  264. // 12. Else if mnfd is not undefined or mxfd is not undefined, then
  265. else if (!min_fraction_digits.is_undefined() || !max_fraction_digits.is_undefined()) {
  266. // a. Set intlObj.[[RoundingType]] to fractionDigits.
  267. intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
  268. // b. Let mnfd be ? DefaultNumberOption(mnfd, 0, 20, undefined).
  269. auto min_digits = TRY(default_number_option(global_object, min_fraction_digits, 0, 20, {}));
  270. // c. Let mxfd be ? DefaultNumberOption(mxfd, 0, 20, undefined).
  271. auto max_digits = TRY(default_number_option(global_object, max_fraction_digits, 0, 20, {}));
  272. // d. If mnfd is undefined, set mnfd to min(mnfdDefault, mxfd).
  273. if (!min_digits.has_value())
  274. min_digits = min(default_min_fraction_digits, *max_digits);
  275. // e. Else if mxfd is undefined, set mxfd to max(mxfdDefault, mnfd).
  276. else if (!max_digits.has_value())
  277. max_digits = max(default_max_fraction_digits, *min_digits);
  278. // f. Else if mnfd is greater than mxfd, throw a RangeError exception.
  279. else if (*min_digits > *max_digits)
  280. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlMinimumExceedsMaximum, *min_digits, *max_digits);
  281. // g. Set intlObj.[[MinimumFractionDigits]] to mnfd.
  282. intl_object.set_min_fraction_digits(*min_digits);
  283. // h. Set intlObj.[[MaximumFractionDigits]] to mxfd.
  284. intl_object.set_max_fraction_digits(*max_digits);
  285. }
  286. // 13. Else if notation is "compact", then
  287. else if (notation == NumberFormat::Notation::Compact) {
  288. // a. Set intlObj.[[RoundingType]] to compactRounding.
  289. intl_object.set_rounding_type(NumberFormat::RoundingType::CompactRounding);
  290. }
  291. // 14. Else,
  292. else {
  293. // a. Set intlObj.[[RoundingType]] to fractionDigits.
  294. intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
  295. // b. Set intlObj.[[MinimumFractionDigits]] to mnfdDefault.
  296. intl_object.set_min_fraction_digits(default_min_fraction_digits);
  297. // c. Set intlObj.[[MaximumFractionDigits]] to mxfdDefault.
  298. intl_object.set_max_fraction_digits(default_max_fraction_digits);
  299. }
  300. return {};
  301. }
  302. // 15.1.2 InitializeNumberFormat ( numberFormat, locales, options ), https://tc39.es/ecma402/#sec-initializenumberformat
  303. ThrowCompletionOr<NumberFormat*> initialize_number_format(GlobalObject& global_object, NumberFormat& number_format, Value locales_value, Value options_value)
  304. {
  305. auto& vm = global_object.vm();
  306. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  307. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  308. // 2. Set options to ? CoerceOptionsToObject(options).
  309. auto* options = TRY(coerce_options_to_object(global_object, options_value));
  310. // 3. Let opt be a new Record.
  311. LocaleOptions opt {};
  312. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  313. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv));
  314. // 5. Set opt.[[localeMatcher]] to matcher.
  315. opt.locale_matcher = matcher;
  316. // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  317. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  318. // 7. If numberingSystem is not undefined, then
  319. if (!numbering_system.is_undefined()) {
  320. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  321. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  322. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  323. // 8. Set opt.[[nu]] to numberingSystem.
  324. opt.nu = numbering_system.as_string().string();
  325. }
  326. // 9. Let localeData be %NumberFormat%.[[LocaleData]].
  327. // 10. Let r be ResolveLocale(%NumberFormat%.[[AvailableLocales]], requestedLocales, opt, %NumberFormat%.[[RelevantExtensionKeys]], localeData).
  328. auto result = resolve_locale(requested_locales, opt, NumberFormat::relevant_extension_keys());
  329. // 11. Set numberFormat.[[Locale]] to r.[[locale]].
  330. number_format.set_locale(move(result.locale));
  331. // 12. Set numberFormat.[[DataLocale]] to r.[[dataLocale]].
  332. number_format.set_data_locale(move(result.data_locale));
  333. // 13. Set numberFormat.[[NumberingSystem]] to r.[[nu]].
  334. number_format.set_numbering_system(result.nu.release_value());
  335. // 14. Perform ? SetNumberFormatUnitOptions(numberFormat, options).
  336. TRY(set_number_format_unit_options(global_object, number_format, *options));
  337. // 15. Let style be numberFormat.[[Style]].
  338. auto style = number_format.style();
  339. int default_min_fraction_digits = 0;
  340. int default_max_fraction_digits = 0;
  341. // 16. If style is "currency", then
  342. if (style == NumberFormat::Style::Currency) {
  343. // a. Let currency be numberFormat.[[Currency]].
  344. auto const& currency = number_format.currency();
  345. // b. Let cDigits be CurrencyDigits(currency).
  346. int digits = currency_digits(currency);
  347. // c. Let mnfdDefault be cDigits.
  348. default_min_fraction_digits = digits;
  349. // d. Let mxfdDefault be cDigits.
  350. default_max_fraction_digits = digits;
  351. }
  352. // 17. Else,
  353. else {
  354. // a. Let mnfdDefault be 0.
  355. default_min_fraction_digits = 0;
  356. // b. If style is "percent", then
  357. // i. Let mxfdDefault be 0.
  358. // c. Else,
  359. // i. Let mxfdDefault be 3.
  360. default_max_fraction_digits = style == NumberFormat::Style::Percent ? 0 : 3;
  361. }
  362. // 18. Let notation be ? GetOption(options, "notation", "string", « "standard", "scientific", "engineering", "compact" », "standard").
  363. auto notation = TRY(get_option(global_object, *options, vm.names.notation, Value::Type::String, { "standard"sv, "scientific"sv, "engineering"sv, "compact"sv }, "standard"sv));
  364. // 19. Set numberFormat.[[Notation]] to notation.
  365. number_format.set_notation(notation.as_string().string());
  366. // 20. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation).
  367. TRY(set_number_format_digit_options(global_object, number_format, *options, default_min_fraction_digits, default_max_fraction_digits, number_format.notation()));
  368. // 21. Let compactDisplay be ? GetOption(options, "compactDisplay", "string", « "short", "long" », "short").
  369. auto compact_display = TRY(get_option(global_object, *options, vm.names.compactDisplay, Value::Type::String, { "short"sv, "long"sv }, "short"sv));
  370. // 22. If notation is "compact", then
  371. if (number_format.notation() == NumberFormat::Notation::Compact) {
  372. // a. Set numberFormat.[[CompactDisplay]] to compactDisplay.
  373. number_format.set_compact_display(compact_display.as_string().string());
  374. }
  375. // 23. Let useGrouping be ? GetOption(options, "useGrouping", "boolean", undefined, true).
  376. auto use_grouping = TRY(get_option(global_object, *options, vm.names.useGrouping, Value::Type::Boolean, {}, true));
  377. // 24. Set numberFormat.[[UseGrouping]] to useGrouping.
  378. number_format.set_use_grouping(use_grouping.as_bool());
  379. // 25. Let signDisplay be ? GetOption(options, "signDisplay", "string", « "auto", "never", "always", "exceptZero" », "auto").
  380. 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));
  381. // 26. Set numberFormat.[[SignDisplay]] to signDisplay.
  382. number_format.set_sign_display(sign_display.as_string().string());
  383. // 27. Return numberFormat.
  384. return &number_format;
  385. }
  386. // 15.1.3 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  387. int currency_digits(StringView currency)
  388. {
  389. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  390. // unit value corresponding to the currency from the list; otherwise, return 2.
  391. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  392. return currency_code->minor_unit.value_or(2);
  393. return 2;
  394. }
  395. // 15.1.5 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  396. FormatResult format_numeric_to_string(NumberFormat& number_format, double number)
  397. {
  398. // 1. If x < 0 or x is -0𝔽, let isNegative be true; else let isNegative be false.
  399. bool is_negative = (number < 0.0) || Value(number).is_negative_zero();
  400. // 2. If isNegative, then
  401. if (is_negative) {
  402. // a. Let x be -x.
  403. number *= -1;
  404. }
  405. RawFormatResult result {};
  406. switch (number_format.rounding_type()) {
  407. // 3. If intlObject.[[RoundingType]] is significantDigits, then
  408. case NumberFormat::RoundingType::SignificantDigits:
  409. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]]).
  410. result = to_raw_precision(number, number_format.min_significant_digits(), number_format.max_significant_digits());
  411. break;
  412. // 4. Else if intlObject.[[RoundingType]] is fractionDigits, then
  413. case NumberFormat::RoundingType::FractionDigits:
  414. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]]).
  415. result = to_raw_fixed(number, number_format.min_fraction_digits(), number_format.max_fraction_digits());
  416. break;
  417. // 5. Else,
  418. case NumberFormat::RoundingType::CompactRounding:
  419. // a. Assert: intlObject.[[RoundingType]] is compactRounding.
  420. // b. Let result be ToRawPrecision(x, 1, 2).
  421. result = to_raw_precision(number, 1, 2);
  422. // c. If result.[[IntegerDigitsCount]] > 1, then
  423. if (result.digits > 1) {
  424. // i. Let result be ToRawFixed(x, 0, 0).
  425. result = to_raw_fixed(number, 0, 0);
  426. }
  427. break;
  428. default:
  429. VERIFY_NOT_REACHED();
  430. }
  431. // 6. Let x be result.[[RoundedNumber]].
  432. number = result.rounded_number;
  433. // 7. Let string be result.[[FormattedString]].
  434. auto string = move(result.formatted_string);
  435. // 8. Let int be result.[[IntegerDigitsCount]].
  436. int digits = result.digits;
  437. // 9. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  438. int min_integer = number_format.min_integer_digits();
  439. // 10. If int < minInteger, then
  440. if (digits < min_integer) {
  441. // a. Let forwardZeros be the String consisting of minInteger–int occurrences of the character "0".
  442. auto forward_zeros = String::repeated('0', min_integer - digits);
  443. // b. Set string to the string-concatenation of forwardZeros and string.
  444. string = String::formatted("{}{}", forward_zeros, string);
  445. }
  446. // 11. If isNegative, then
  447. if (is_negative) {
  448. // a. Let x be -x.
  449. number *= -1;
  450. }
  451. // 12. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  452. return { move(string), number };
  453. }
  454. // 15.1.6 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  455. Vector<PatternPartition> partition_number_pattern(NumberFormat& number_format, double number)
  456. {
  457. // 1. Let exponent be 0.
  458. int exponent = 0;
  459. String formatted_string;
  460. // 2. If x is NaN, then
  461. if (Value(number).is_nan()) {
  462. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  463. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "nan"sv).value_or("NaN"sv);
  464. }
  465. // 3. Else if x is a non-finite Number, then
  466. else if (!Value(number).is_finite_number()) {
  467. // a. Let n be an ILD String value indicating infinity.
  468. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "infinity"sv).value_or("infinity"sv);
  469. }
  470. // 4. Else,
  471. else {
  472. // a. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  473. if (number_format.style() == NumberFormat::Style::Percent)
  474. number = number * 100;
  475. // b. Let exponent be ComputeExponent(numberFormat, x).
  476. exponent = compute_exponent(number_format, number);
  477. // c. Let x be x × 10^(-exponent).
  478. number *= pow(10, -exponent);
  479. // d. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  480. auto format_number_result = format_numeric_to_string(number_format, number);
  481. // e. Let n be formatNumberResult.[[FormattedString]].
  482. formatted_string = move(format_number_result.formatted_string);
  483. // f. Let x be formatNumberResult.[[RoundedNumber]].
  484. number = format_number_result.rounded_number;
  485. }
  486. // 5. Let pattern be GetNumberFormatPattern(numberFormat, x).
  487. auto pattern = get_number_format_pattern(number_format, number);
  488. if (!pattern.has_value())
  489. return {};
  490. // 6. Let result be a new empty List.
  491. Vector<PatternPartition> result;
  492. // 7. Let patternParts be PartitionPattern(pattern).
  493. auto pattern_parts = partition_pattern(*pattern);
  494. // 8. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  495. for (auto& pattern_part : pattern_parts) {
  496. // a. Let p be patternPart.[[Type]].
  497. auto part = pattern_part.type;
  498. // b. If p is "literal", then
  499. if (part == "literal"sv) {
  500. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  501. result.append({ part, move(pattern_part.value) });
  502. }
  503. // c. Else if p is equal to "number", then
  504. else if (part == "number"sv) {
  505. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  506. auto notation_sub_parts = partition_notation_sub_pattern(number_format, number, formatted_string, exponent);
  507. // ii. Append all elements of notationSubParts to result.
  508. result.extend(move(notation_sub_parts));
  509. }
  510. // d. Else if p is equal to "plusSign", then
  511. else if (part == "plusSign"sv) {
  512. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  513. auto plus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "plusSign"sv).value_or("+"sv);
  514. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  515. result.append({ part, plus_sign_symbol });
  516. }
  517. // e. Else if p is equal to "minusSign", then
  518. else if (part == "minusSign"sv) {
  519. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  520. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "minusSign"sv).value_or("-"sv);
  521. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  522. result.append({ part, minus_sign_symbol });
  523. }
  524. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  525. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  526. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  527. auto percent_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "percentSign"sv).value_or("%"sv);
  528. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  529. result.append({ part, percent_sign_symbol });
  530. }
  531. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  532. else if ((part == "unitPrefix"sv) && (number_format.style() == NumberFormat::Style::Unit)) {
  533. // i. Let unit be numberFormat.[[Unit]].
  534. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  535. // 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.
  536. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  537. // FIXME: LibUnicode will need to parse the cldr-units package.
  538. }
  539. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  540. else if ((part == "unitSuffix"sv) && (number_format.style() == NumberFormat::Style::Unit)) {
  541. // i. Let unit be numberFormat.[[Unit]].
  542. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  543. // iii. Let mu be an ILD String value representing unit after x in unitDisplay form, which may depend on x in languages having different plural forms.
  544. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  545. // FIXME: LibUnicode will need to parse the cldr-units package.
  546. }
  547. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  548. else if ((part == "currencyCode"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  549. // i. Let currency be numberFormat.[[Currency]].
  550. // ii. Let cd be currency.
  551. // iii. Append a new Record { [[Type]]: "currency", [[Value]]: cd } as the last element of result.
  552. result.append({ part, number_format.currency() });
  553. }
  554. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  555. else if ((part == "currencyPrefix"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  556. // i. Let currency be numberFormat.[[Currency]].
  557. // ii. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  558. // iii. Let cd be an ILD String value representing currency before x in currencyDisplay form, which may depend on x in languages having different plural forms.
  559. // iv. Append a new Record { [[Type]]: "currency", [[Value]]: cd } as the last element of result.
  560. // FIXME: LibUnicode will need to parse currencies.json and the "currencySpacing/beforeCurrency" object from numbers.json.
  561. }
  562. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  563. else if ((part == "currencySuffix"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  564. // i. Let currency be numberFormat.[[Currency]].
  565. // ii. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  566. // iii. Let cd be an ILD String value representing currency after x in currencyDisplay form, which may depend on x in languages having different plural forms. If the implementation does not have such a representation of currency, use currency itself.
  567. // iv. Append a new Record { [[Type]]: "currency", [[Value]]: cd } as the last element of result.
  568. // FIXME: LibUnicode will need to parse currencies.json and the "currencySpacing/afterCurrency" object from numbers.json.
  569. }
  570. // l. Else,
  571. else {
  572. // i. Let unknown be an ILND String based on x and p.
  573. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  574. // LibUnicode doesn't generate any "unknown" patterns.
  575. VERIFY_NOT_REACHED();
  576. }
  577. }
  578. // 9. Return result.
  579. return result;
  580. }
  581. static String replace_digits_for_number_format(NumberFormat& number_format, String formatted_string)
  582. {
  583. // https://tc39.es/ecma402/#table-numbering-system-digits
  584. static HashMap<StringView, AK::Array<u32, 10>> s_numbering_system_digits = {
  585. { "adlm"sv, { 0x1e950, 0x1e951, 0x1e952, 0x1e953, 0x1e954, 0x1e955, 0x1e956, 0x1e957, 0x1e958, 0x1e959 } },
  586. { "ahom"sv, { 0x11730, 0x11731, 0x11732, 0x11733, 0x11734, 0x11735, 0x11736, 0x11737, 0x11738, 0x11739 } },
  587. { "arab"sv, { 0x660, 0x661, 0x662, 0x663, 0x664, 0x665, 0x666, 0x667, 0x668, 0x669 } },
  588. { "arabext"sv, { 0x6f0, 0x6f1, 0x6f2, 0x6f3, 0x6f4, 0x6f5, 0x6f6, 0x6f7, 0x6f8, 0x6f9 } },
  589. { "bali"sv, { 0x1b50, 0x1b51, 0x1b52, 0x1b53, 0x1b54, 0x1b55, 0x1b56, 0x1b57, 0x1b58, 0x1b59 } },
  590. { "beng"sv, { 0x9e6, 0x9e7, 0x9e8, 0x9e9, 0x9ea, 0x9eb, 0x9ec, 0x9ed, 0x9ee, 0x9ef } },
  591. { "bhks"sv, { 0x11c50, 0x11c51, 0x11c52, 0x11c53, 0x11c54, 0x11c55, 0x11c56, 0x11c57, 0x11c58, 0x11c59 } },
  592. { "brah"sv, { 0x11066, 0x11067, 0x11068, 0x11069, 0x1106a, 0x1106b, 0x1106c, 0x1106d, 0x1106e, 0x1106f } },
  593. { "cakm"sv, { 0x11136, 0x11137, 0x11138, 0x11139, 0x1113a, 0x1113b, 0x1113c, 0x1113d, 0x1113e, 0x1113f } },
  594. { "cham"sv, { 0xaa50, 0xaa51, 0xaa52, 0xaa53, 0xaa54, 0xaa55, 0xaa56, 0xaa57, 0xaa58, 0xaa59 } },
  595. { "deva"sv, { 0x966, 0x967, 0x968, 0x969, 0x96a, 0x96b, 0x96c, 0x96d, 0x96e, 0x96f } },
  596. { "diak"sv, { 0x11950, 0x11951, 0x11952, 0x11953, 0x11954, 0x11955, 0x11956, 0x11957, 0x11958, 0x11959 } },
  597. { "fullwide"sv, { 0xff10, 0xff11, 0xff12, 0xff13, 0xff14, 0xff15, 0xff16, 0xff17, 0xff18, 0xff19 } },
  598. { "gong"sv, { 0x11da0, 0x11da1, 0x11da2, 0x11da3, 0x11da4, 0x11da5, 0x11da6, 0x11da7, 0x11da8, 0x11da9 } },
  599. { "gonm"sv, { 0x11d50, 0x11d51, 0x11d52, 0x11d53, 0x11d54, 0x11d55, 0x11d56, 0x11d57, 0x11d58, 0x11d59 } },
  600. { "gujr"sv, { 0xae6, 0xae7, 0xae8, 0xae9, 0xaea, 0xaeb, 0xaec, 0xaed, 0xaee, 0xaef } },
  601. { "guru"sv, { 0xa66, 0xa67, 0xa68, 0xa69, 0xa6a, 0xa6b, 0xa6c, 0xa6d, 0xa6e, 0xa6f } },
  602. { "hanidec"sv, { 0x3007, 0x4e00, 0x4e8c, 0x4e09, 0x56db, 0x4e94, 0x516d, 0x4e03, 0x516b, 0x4e5d } },
  603. { "hmng"sv, { 0x16b50, 0x16b51, 0x16b52, 0x16b53, 0x16b54, 0x16b55, 0x16b56, 0x16b57, 0x16b58, 0x16b59 } },
  604. { "hmnp"sv, { 0x1e140, 0x1e141, 0x1e142, 0x1e143, 0x1e144, 0x1e145, 0x1e146, 0x1e147, 0x1e148, 0x1e149 } },
  605. { "java"sv, { 0xa9d0, 0xa9d1, 0xa9d2, 0xa9d3, 0xa9d4, 0xa9d5, 0xa9d6, 0xa9d7, 0xa9d8, 0xa9d9 } },
  606. { "kali"sv, { 0xa900, 0xa901, 0xa902, 0xa903, 0xa904, 0xa905, 0xa906, 0xa907, 0xa908, 0xa909 } },
  607. { "khmr"sv, { 0x17e0, 0x17e1, 0x17e2, 0x17e3, 0x17e4, 0x17e5, 0x17e6, 0x17e7, 0x17e8, 0x17e9 } },
  608. { "knda"sv, { 0xce6, 0xce7, 0xce8, 0xce9, 0xcea, 0xceb, 0xcec, 0xced, 0xcee, 0xcef } },
  609. { "lana"sv, { 0x1a80, 0x1a81, 0x1a82, 0x1a83, 0x1a84, 0x1a85, 0x1a86, 0x1a87, 0x1a88, 0x1a89 } },
  610. { "lanatham"sv, { 0x1a90, 0x1a91, 0x1a92, 0x1a93, 0x1a94, 0x1a95, 0x1a96, 0x1a97, 0x1a98, 0x1a99 } },
  611. { "laoo"sv, { 0xed0, 0xed1, 0xed2, 0xed3, 0xed4, 0xed5, 0xed6, 0xed7, 0xed8, 0xed9 } },
  612. { "latn"sv, { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 } },
  613. { "lepc"sv, { 0x1c40, 0x1c41, 0x1c42, 0x1c43, 0x1c44, 0x1c45, 0x1c46, 0x1c47, 0x1c48, 0x1c49 } },
  614. { "limb"sv, { 0x1946, 0x1947, 0x1948, 0x1949, 0x194a, 0x194b, 0x194c, 0x194d, 0x194e, 0x194f } },
  615. { "mathbold"sv, { 0x1d7ce, 0x1d7cf, 0x1d7d0, 0x1d7d1, 0x1d7d2, 0x1d7d3, 0x1d7d4, 0x1d7d5, 0x1d7d6, 0x1d7d7 } },
  616. { "mathdbl"sv, { 0x1d7d8, 0x1d7d9, 0x1d7da, 0x1d7db, 0x1d7dc, 0x1d7dd, 0x1d7de, 0x1d7df, 0x1d7e0, 0x1d7e1 } },
  617. { "mathmono"sv, { 0x1d7f6, 0x1d7f7, 0x1d7f8, 0x1d7f9, 0x1d7fa, 0x1d7fb, 0x1d7fc, 0x1d7fd, 0x1d7fe, 0x1d7ff } },
  618. { "mathsanb"sv, { 0x1d7ec, 0x1d7ed, 0x1d7ee, 0x1d7ef, 0x1d7f0, 0x1d7f1, 0x1d7f2, 0x1d7f3, 0x1d7f4, 0x1d7f5 } },
  619. { "mathsans"sv, { 0x1d7e2, 0x1d7e3, 0x1d7e4, 0x1d7e5, 0x1d7e6, 0x1d7e7, 0x1d7e8, 0x1d7e9, 0x1d7ea, 0x1d7eb } },
  620. { "mlym"sv, { 0xd66, 0xd67, 0xd68, 0xd69, 0xd6a, 0xd6b, 0xd6c, 0xd6d, 0xd6e, 0xd6f } },
  621. { "modi"sv, { 0x11650, 0x11651, 0x11652, 0x11653, 0x11654, 0x11655, 0x11656, 0x11657, 0x11658, 0x11659 } },
  622. { "mong"sv, { 0x1810, 0x1811, 0x1812, 0x1813, 0x1814, 0x1815, 0x1816, 0x1817, 0x1818, 0x1819 } },
  623. { "mroo"sv, { 0x16a60, 0x16a61, 0x16a62, 0x16a63, 0x16a64, 0x16a65, 0x16a66, 0x16a67, 0x16a68, 0x16a69 } },
  624. { "mtei"sv, { 0xabf0, 0xabf1, 0xabf2, 0xabf3, 0xabf4, 0xabf5, 0xabf6, 0xabf7, 0xabf8, 0xabf9 } },
  625. { "mymr"sv, { 0x1040, 0x1041, 0x1042, 0x1043, 0x1044, 0x1045, 0x1046, 0x1047, 0x1048, 0x1049 } },
  626. { "mymrshan"sv, { 0x1090, 0x1091, 0x1092, 0x1093, 0x1094, 0x1095, 0x1096, 0x1097, 0x1098, 0x1099 } },
  627. { "mymrtlng"sv, { 0xa9f0, 0xa9f1, 0xa9f2, 0xa9f3, 0xa9f4, 0xa9f5, 0xa9f6, 0xa9f7, 0xa9f8, 0xa9f9 } },
  628. { "newa"sv, { 0x11450, 0x11451, 0x11452, 0x11453, 0x11454, 0x11455, 0x11456, 0x11457, 0x11458, 0x11459 } },
  629. { "nkoo"sv, { 0x7c0, 0x7c1, 0x7c2, 0x7c3, 0x7c4, 0x7c5, 0x7c6, 0x7c7, 0x7c8, 0x7c9 } },
  630. { "olck"sv, { 0x1c50, 0x1c51, 0x1c52, 0x1c53, 0x1c54, 0x1c55, 0x1c56, 0x1c57, 0x1c58, 0x1c59 } },
  631. { "orya"sv, { 0xb66, 0xb67, 0xb68, 0xb69, 0xb6a, 0xb6b, 0xb6c, 0xb6d, 0xb6e, 0xb6f } },
  632. { "osma"sv, { 0x104a0, 0x104a1, 0x104a2, 0x104a3, 0x104a4, 0x104a5, 0x104a6, 0x104a7, 0x104a8, 0x104a9 } },
  633. { "rohg"sv, { 0x10d30, 0x10d31, 0x10d32, 0x10d33, 0x10d34, 0x10d35, 0x10d36, 0x10d37, 0x10d38, 0x10d39 } },
  634. { "saur"sv, { 0xa8d0, 0xa8d1, 0xa8d2, 0xa8d3, 0xa8d4, 0xa8d5, 0xa8d6, 0xa8d7, 0xa8d8, 0xa8d9 } },
  635. { "segment"sv, { 0x1fbf0, 0x1fbf1, 0x1fbf2, 0x1fbf3, 0x1fbf4, 0x1fbf5, 0x1fbf6, 0x1fbf7, 0x1fbf8, 0x1fbf9 } },
  636. { "shrd"sv, { 0x111d0, 0x111d1, 0x111d2, 0x111d3, 0x111d4, 0x111d5, 0x111d6, 0x111d7, 0x111d8, 0x111d9 } },
  637. { "sind"sv, { 0x112f0, 0x112f1, 0x112f2, 0x112f3, 0x112f4, 0x112f5, 0x112f6, 0x112f7, 0x112f8, 0x112f9 } },
  638. { "sinh"sv, { 0xde6, 0xde7, 0xde8, 0xde9, 0xdea, 0xdeb, 0xdec, 0xded, 0xdee, 0xdef } },
  639. { "sora"sv, { 0x110f0, 0x110f1, 0x110f2, 0x110f3, 0x110f4, 0x110f5, 0x110f6, 0x110f7, 0x110f8, 0x110f9 } },
  640. { "sund"sv, { 0x1bb0, 0x1bb1, 0x1bb2, 0x1bb3, 0x1bb4, 0x1bb5, 0x1bb6, 0x1bb7, 0x1bb8, 0x1bb9 } },
  641. { "takr"sv, { 0x116c0, 0x116c1, 0x116c2, 0x116c3, 0x116c4, 0x116c5, 0x116c6, 0x116c7, 0x116c8, 0x116c9 } },
  642. { "talu"sv, { 0x19d0, 0x19d1, 0x19d2, 0x19d3, 0x19d4, 0x19d5, 0x19d6, 0x19d7, 0x19d8, 0x19d9 } },
  643. { "tamldec"sv, { 0xbe6, 0xbe7, 0xbe8, 0xbe9, 0xbea, 0xbeb, 0xbec, 0xbed, 0xbee, 0xbef } },
  644. { "telu"sv, { 0xc66, 0xc67, 0xc68, 0xc69, 0xc6a, 0xc6b, 0xc6c, 0xc6d, 0xc6e, 0xc6f } },
  645. { "thai"sv, { 0xe50, 0xe51, 0xe52, 0xe53, 0xe54, 0xe55, 0xe56, 0xe57, 0xe58, 0xe59 } },
  646. { "tibt"sv, { 0xf20, 0xf21, 0xf22, 0xf23, 0xf24, 0xf25, 0xf26, 0xf27, 0xf28, 0xf29 } },
  647. { "tirh"sv, { 0x114d0, 0x114d1, 0x114d2, 0x114d3, 0x114d4, 0x114d5, 0x114d6, 0x114d7, 0x114d8, 0x114d9 } },
  648. { "vaii"sv, { 0xa620, 0xa621, 0xa622, 0xa623, 0xa624, 0xa625, 0xa626, 0xa627, 0xa628, 0xa629 } },
  649. { "wara"sv, { 0x118e0, 0x118e1, 0x118e2, 0x118e3, 0x118e4, 0x118e5, 0x118e6, 0x118e7, 0x118e8, 0x118e9 } },
  650. { "wcho"sv, { 0x1e2f0, 0x1e2f1, 0x1e2f2, 0x1e2f3, 0x1e2f4, 0x1e2f5, 0x1e2f6, 0x1e2f7, 0x1e2f8, 0x1e2f9 } },
  651. };
  652. auto digits = s_numbering_system_digits.get(number_format.numbering_system());
  653. if (!digits.has_value())
  654. digits = s_numbering_system_digits.get("latn"sv);
  655. VERIFY(digits.has_value());
  656. StringBuilder builder;
  657. for (auto& ch : formatted_string) {
  658. if (is_ascii_digit(ch)) {
  659. u32 digit = digits->at(parse_ascii_digit(ch));
  660. builder.append_code_point(digit);
  661. } else {
  662. builder.append(ch);
  663. }
  664. }
  665. return builder.build();
  666. }
  667. // 15.1.7 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  668. Vector<PatternPartition> partition_notation_sub_pattern(NumberFormat& number_format, double number, String formatted_string, int exponent)
  669. {
  670. // 1. Let result be a new empty List.
  671. Vector<PatternPartition> result;
  672. // 2. If x is NaN, then
  673. if (Value(number).is_nan()) {
  674. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  675. result.append({ "nan"sv, move(formatted_string) });
  676. }
  677. // 3. Else if x is a non-finite Number, then
  678. else if (!Value(number).is_finite_number()) {
  679. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  680. result.append({ "infinity"sv, move(formatted_string) });
  681. }
  682. // 4. Else,
  683. else {
  684. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  685. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  686. // b. Let patternParts be PartitionPattern(notationSubPattern).
  687. auto pattern_parts = partition_pattern(notation_sub_pattern);
  688. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  689. for (auto& pattern_part : pattern_parts) {
  690. // i. Let p be patternPart.[[Type]].
  691. auto part = pattern_part.type;
  692. // ii. If p is "literal", then
  693. if (part == "literal"sv) {
  694. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  695. result.append({ part, move(pattern_part.value) });
  696. }
  697. // iii. Else if p is equal to "number", then
  698. else if (part == "number"sv) {
  699. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 10 below, then
  700. // 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.
  701. // b. Replace each digit in n with the value of digits[digit].
  702. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  703. formatted_string = replace_digits_for_number_format(number_format, move(formatted_string));
  704. // 3. Let decimalSepIndex be ! StringIndexOf(n, ".", 0).
  705. auto decimal_sep_index = formatted_string.find('.');
  706. StringView integer;
  707. Optional<StringView> fraction;
  708. // 4. If decimalSepIndex > 0, then
  709. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  710. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  711. integer = formatted_string.substring_view(0, *decimal_sep_index);
  712. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  713. fraction = formatted_string.substring_view(*decimal_sep_index + 1);
  714. }
  715. // 5. Else,
  716. else {
  717. // a. Let integer be n.
  718. integer = formatted_string;
  719. // b. Let fraction be undefined.
  720. }
  721. // 6. If the numberFormat.[[UseGrouping]] is true, then
  722. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  723. // 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.
  724. // c. Assert: The number of elements in groups List is greater than 0.
  725. // d. Repeat, while groups List is not empty,
  726. // i. Remove the first element from groups and let integerGroup be the value of that element.
  727. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  728. // iii. If groups List is not empty, then
  729. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  730. // 7. Else,
  731. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  732. // FIXME: Implement grouping.
  733. result.append({ "integer"sv, integer });
  734. // 8. If fraction is not undefined, then
  735. if (fraction.has_value()) {
  736. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  737. auto decimal_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), "decimal"sv).value_or("."sv);
  738. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  739. result.append({ "decimal"sv, decimal_sep_symbol });
  740. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  741. result.append({ "fraction"sv, fraction.release_value() });
  742. }
  743. }
  744. // iv. Else if p is equal to "compactSymbol", then
  745. else if (part == "compactSymbol"sv) {
  746. // 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.
  747. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  748. // FIXME: Implement this when GetNotationSubPattern is fully implemented.
  749. }
  750. // v. Else if p is equal to "compactName", then
  751. else if (part == "compactName"sv) {
  752. // 1. Let compactName be an ILD string representing exponent in long 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 "{compactName}" placeholder.
  753. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactName } as the last element of result.
  754. // FIXME: Implement this when GetNotationSubPattern is fully implemented.
  755. }
  756. // vi. Else if p is equal to "scientificSeparator", then
  757. else if (part == "scientificSeparator"sv) {
  758. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  759. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  760. // FIXME: Implement this when GetNotationSubPattern is fully implemented.
  761. }
  762. // vii. Else if p is equal to "scientificExponent", then
  763. else if (part == "scientificExponent"sv) {
  764. // 1. If exponent < 0, then
  765. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  766. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  767. // c. Let exponent be -exponent.
  768. // 2. Let exponentResult be ToRawFixed(exponent, 1, 0, 0).
  769. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  770. // FIXME: Implement this when GetNotationSubPattern is fully implemented.
  771. }
  772. // viii. Else,
  773. else {
  774. // 1. Let unknown be an ILND String based on x and p.
  775. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  776. // FIXME: Implement this when GetNotationSubPattern is fully implemented.
  777. }
  778. }
  779. }
  780. // 5. Return result.
  781. return result;
  782. }
  783. // 15.1.8 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  784. String format_numeric(NumberFormat& number_format, double number)
  785. {
  786. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  787. // Note: Our implementation of PartitionNumberPattern does not throw.
  788. auto parts = partition_number_pattern(number_format, number);
  789. // 2. Let result be the empty String.
  790. StringBuilder result;
  791. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  792. for (auto& part : parts) {
  793. // a. Set result to the string-concatenation of result and part.[[Value]].
  794. result.append(move(part.value));
  795. }
  796. // 4. Return result.
  797. return result.build();
  798. }
  799. static String cut_trailing_zeroes(StringView string, int cut)
  800. {
  801. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  802. // Repeat, while cut > 0 and the last character of m is "0",
  803. while ((cut > 0) && string.ends_with('0')) {
  804. // Remove the last character from m.
  805. string = string.substring_view(0, string.length() - 1);
  806. // Decrease cut by 1.
  807. --cut;
  808. }
  809. // If the last character of m is ".", then
  810. if (string.ends_with('.')) {
  811. // Remove the last character from m.
  812. string = string.substring_view(0, string.length() - 1);
  813. }
  814. return string.to_string();
  815. }
  816. // 15.1.10 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  817. RawFormatResult to_raw_precision(double number, int min_precision, int max_precision)
  818. {
  819. RawFormatResult result {};
  820. // 1. Let p be maxPrecision.
  821. int precision = max_precision;
  822. int exponent = 0;
  823. // 2. If x = 0, then
  824. if (number == 0.0) {
  825. // a. Let m be the String consisting of p occurrences of the character "0".
  826. result.formatted_string = String::repeated('0', precision);
  827. // b. Let e be 0.
  828. exponent = 0;
  829. // c. Let xFinal be 0.
  830. result.rounded_number = 0;
  831. }
  832. // 3. Else,
  833. else {
  834. // FIXME: The result of these steps isn't entirely accurate for large values of 'p' (which
  835. // defaults to 21, resulting in numbers on the order of 10^21). Either AK::format or
  836. // our Number::toString AO (double_to_string in Value.cpp) will need to be improved
  837. // to produce more accurate results.
  838. // a. Let e be the base 10 logarithm of x rounded down to the nearest integer.
  839. exponent = log10floor(number);
  840. double power = pow(10, exponent - precision + 1);
  841. // b. Let n be an integer such that 10^(p–1) ≤ n < 10^p and for which the exact mathematical value of n × 10^(e–p+1) – x
  842. // is as close to zero as possible. If there is more than one such n, pick the one for which n × 10^(e–p+1) is larger.
  843. double n = round(number / power);
  844. // c. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  845. result.formatted_string = Value(n).to_string_without_side_effects();
  846. // d. Let xFinal be n × 10^(e–p+1).
  847. result.rounded_number = n * power;
  848. }
  849. // 4. If e ≥ p–1, then
  850. if (exponent >= (precision - 1)) {
  851. // a. Let m be the string-concatenation of m and e–p+1 occurrences of the character "0".
  852. result.formatted_string = String::formatted(
  853. "{}{}",
  854. result.formatted_string,
  855. String::repeated('0', exponent - precision + 1));
  856. // b. Let int be e+1.
  857. result.digits = exponent + 1;
  858. }
  859. // 5. Else if e ≥ 0, then
  860. else if (exponent >= 0) {
  861. // 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.
  862. result.formatted_string = String::formatted(
  863. "{}.{}",
  864. result.formatted_string.substring_view(0, exponent + 1),
  865. result.formatted_string.substring_view(exponent + 1));
  866. // b. Let int be e+1.
  867. result.digits = exponent + 1;
  868. }
  869. // 6. Else,
  870. else {
  871. // a. Assert: e < 0.
  872. // b. Let m be the string-concatenation of the String value "0.", –(e+1) occurrences of the character "0", and m.
  873. result.formatted_string = String::formatted(
  874. "0.{}{}",
  875. String::repeated('0', -1 * (exponent + 1)),
  876. result.formatted_string);
  877. // c. Let int be 1.
  878. result.digits = 1;
  879. }
  880. // 7. If m contains the character ".", and maxPrecision > minPrecision, then
  881. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  882. // a. Let cut be maxPrecision – minPrecision.
  883. int cut = max_precision - min_precision;
  884. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  885. }
  886. // 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  887. return result;
  888. }
  889. // 15.1.11 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  890. // NOTE: The spec has a mistake here. The minInteger parameter is unused and is not provided by FormatNumericToString.
  891. RawFormatResult to_raw_fixed(double number, int min_fraction, int max_fraction)
  892. {
  893. RawFormatResult result {};
  894. // 1. Let f be maxFraction.
  895. int fraction = max_fraction;
  896. double power = pow(10, fraction);
  897. // 2. 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.
  898. double n = round(number * power);
  899. // 3. Let xFinal be n / 10^f.
  900. result.rounded_number = n / power;
  901. // 4. 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).
  902. result.formatted_string = n == 0.0 ? String("0"sv) : Value(n).to_string_without_side_effects();
  903. // 5. If f ≠ 0, then
  904. if (fraction != 0) {
  905. // a. Let k be the number of characters in m.
  906. auto decimals = result.formatted_string.length();
  907. // b. If k ≤ f, then
  908. if (decimals <= static_cast<size_t>(fraction)) {
  909. // i. Let z be the String value consisting of f+1–k occurrences of the character "0".
  910. auto zeroes = String::repeated('0', fraction + 1 - decimals);
  911. // ii. Let m be the string-concatenation of z and m.
  912. result.formatted_string = String::formatted("{}{}", zeroes, result.formatted_string);
  913. // iii. Let k be f+1.
  914. decimals = fraction + 1;
  915. }
  916. // c. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
  917. auto a = result.formatted_string.substring_view(0, decimals - fraction);
  918. auto b = result.formatted_string.substring_view(decimals - fraction, fraction);
  919. // d. Let m be the string-concatenation of a, ".", and b.
  920. result.formatted_string = String::formatted("{}.{}", a, b);
  921. // e. Let int be the number of characters in a.
  922. result.digits = a.length();
  923. }
  924. // 6. Else, let int be the number of characters in m.
  925. else {
  926. result.digits = result.formatted_string.length();
  927. }
  928. // 7. Let cut be maxFraction – minFraction.
  929. int cut = max_fraction - min_fraction;
  930. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  931. // 10. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  932. return result;
  933. }
  934. // 15.1.13 SetNumberFormatUnitOptions ( intlObj, options ), https://tc39.es/ecma402/#sec-setnumberformatunitoptions
  935. ThrowCompletionOr<void> set_number_format_unit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options)
  936. {
  937. auto& vm = global_object.vm();
  938. // 1. Assert: Type(intlObj) is Object.
  939. // 2. Assert: Type(options) is Object.
  940. // 3. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
  941. auto style = TRY(get_option(global_object, options, vm.names.style, Value::Type::String, { "decimal"sv, "percent"sv, "currency"sv, "unit"sv }, "decimal"sv));
  942. // 4. Set intlObj.[[Style]] to style.
  943. intl_object.set_style(style.as_string().string());
  944. // 5. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
  945. auto currency = TRY(get_option(global_object, options, vm.names.currency, Value::Type::String, {}, Empty {}));
  946. // 6. If currency is undefined, then
  947. if (currency.is_undefined()) {
  948. // a. If style is "currency", throw a TypeError exception.
  949. if (intl_object.style() == NumberFormat::Style::Currency)
  950. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "currency"sv, "style"sv, style);
  951. }
  952. // 7. Else,
  953. // a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
  954. else if (!is_well_formed_currency_code(currency.as_string().string()))
  955. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, currency, "currency"sv);
  956. // 8. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
  957. 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));
  958. // 9. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
  959. auto currency_sign = TRY(get_option(global_object, options, vm.names.currencySign, Value::Type::String, { "standard"sv, "accounting"sv }, "standard"sv));
  960. // 10. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
  961. auto unit = TRY(get_option(global_object, options, vm.names.unit, Value::Type::String, {}, Empty {}));
  962. // 11. If unit is undefined, then
  963. if (unit.is_undefined()) {
  964. // a. If style is "unit", throw a TypeError exception.
  965. if (intl_object.style() == NumberFormat::Style::Unit)
  966. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "unit"sv, "style"sv, style);
  967. }
  968. // 12. Else,
  969. // a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
  970. else if (!is_well_formed_unit_identifier(unit.as_string().string()))
  971. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "unit"sv);
  972. // 13. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
  973. auto unit_display = TRY(get_option(global_object, options, vm.names.unitDisplay, Value::Type::String, { "short"sv, "narrow"sv, "long"sv }, "short"sv));
  974. // 14. If style is "currency", then
  975. if (intl_object.style() == NumberFormat::Style::Currency) {
  976. // a. Let currency be the result of converting currency to upper case as specified in 6.1.
  977. // b. Set intlObj.[[Currency]] to currency.
  978. intl_object.set_currency(currency.as_string().string().to_uppercase());
  979. // c. Set intlObj.[[CurrencyDisplay]] to currencyDisplay.
  980. intl_object.set_currency_display(currency_display.as_string().string());
  981. // d. Set intlObj.[[CurrencySign]] to currencySign.
  982. intl_object.set_currency_sign(currency_sign.as_string().string());
  983. }
  984. // 15. If style is "unit", then
  985. if (intl_object.style() == NumberFormat::Style::Unit) {
  986. // a. Set intlObj.[[Unit]] to unit.
  987. intl_object.set_unit(unit.as_string().string());
  988. // b. Set intlObj.[[UnitDisplay]] to unitDisplay.
  989. intl_object.set_unit_display(unit_display.as_string().string());
  990. }
  991. return {};
  992. }
  993. // 15.1.14 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  994. Optional<StringView> get_number_format_pattern(NumberFormat& number_format, double number)
  995. {
  996. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  997. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  998. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  999. // 4. Let patterns be dataLocaleData.[[patterns]].
  1000. // 5. Assert: patterns is a Record (see 15.3.3).
  1001. Optional<Unicode::NumberFormat> patterns;
  1002. // 6. Let style be numberFormat.[[Style]].
  1003. switch (number_format.style()) {
  1004. // 7. If style is "percent", then
  1005. case NumberFormat::Style::Percent:
  1006. // a. Let patterns be patterns.[[percent]].
  1007. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Percent);
  1008. break;
  1009. // 8. Else if style is "unit", then
  1010. case NumberFormat::Style::Unit:
  1011. // a. Let unit be numberFormat.[[Unit]].
  1012. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1013. // c. Let patterns be patterns.[[unit]].
  1014. // d. If patterns doesn't have a field [[<unit>]], then
  1015. // i. Let unit be "fallback".
  1016. // e. Let patterns be patterns.[[<unit>]].
  1017. // f. Let patterns be patterns.[[<unitDisplay>]].
  1018. // FIXME: LibUnicode will need to parse the cldr-units package.
  1019. break;
  1020. // 9. Else if style is "currency", then
  1021. case NumberFormat::Style::Currency:
  1022. // a. Let currency be numberFormat.[[Currency]].
  1023. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1024. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1025. // d. Let patterns be patterns.[[currency]].
  1026. // e. If patterns doesn't have a field [[<currency>]], then
  1027. // i. Let currency be "fallback".
  1028. // f. Let patterns be patterns.[[<currency>]].
  1029. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1030. // h. Let patterns be patterns.[[<currencySign>]].
  1031. switch (number_format.currency_sign()) {
  1032. case NumberFormat::CurrencySign::Standard:
  1033. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Currency);
  1034. break;
  1035. case NumberFormat::CurrencySign::Accounting:
  1036. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Accounting);
  1037. break;
  1038. }
  1039. break;
  1040. // 10. Else,
  1041. case NumberFormat::Style::Decimal:
  1042. // a. Assert: style is "decimal".
  1043. // b. Let patterns be patterns.[[decimal]].
  1044. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Decimal);
  1045. break;
  1046. default:
  1047. VERIFY_NOT_REACHED();
  1048. }
  1049. if (!patterns.has_value())
  1050. return {};
  1051. StringView pattern;
  1052. Value number_value(number);
  1053. bool is_positive_zero = number_value.is_positive_zero();
  1054. bool is_negative_zero = number_value.is_negative_zero();
  1055. bool is_nan = number_value.is_nan();
  1056. // 11. Let signDisplay be numberFormat.[[SignDisplay]].
  1057. switch (number_format.sign_display()) {
  1058. // 12. If signDisplay is "never", then
  1059. case NumberFormat::SignDisplay::Never:
  1060. // a. Let pattern be patterns.[[zeroPattern]].
  1061. pattern = patterns->zero_format;
  1062. break;
  1063. // 13. Else if signDisplay is "auto", then
  1064. case NumberFormat::SignDisplay::Auto:
  1065. // a. If x is 0 or x > 0 or x is NaN, then
  1066. if (is_positive_zero || (number > 0) || is_nan) {
  1067. // i. Let pattern be patterns.[[zeroPattern]].
  1068. pattern = patterns->zero_format;
  1069. }
  1070. // b. Else,
  1071. else {
  1072. // i. Let pattern be patterns.[[negativePattern]].
  1073. pattern = patterns->negative_format;
  1074. }
  1075. break;
  1076. // 14. Else if signDisplay is "always", then
  1077. case NumberFormat::SignDisplay::Always:
  1078. // a. If x is 0 or x > 0 or x is NaN, then
  1079. if (is_positive_zero || (number > 0) || is_nan) {
  1080. // i. Let pattern be patterns.[[positivePattern]].
  1081. pattern = patterns->positive_format;
  1082. }
  1083. // b. Else,
  1084. else {
  1085. // i. Let pattern be patterns.[[negativePattern]].
  1086. pattern = patterns->negative_format;
  1087. }
  1088. break;
  1089. // 15. Else,
  1090. case NumberFormat::SignDisplay::ExceptZero:
  1091. // a. Assert: signDisplay is "exceptZero".
  1092. // b. If x is 0 or x is -0 or x is NaN, then
  1093. if (is_positive_zero || is_negative_zero || is_nan) {
  1094. // i. Let pattern be patterns.[[zeroPattern]].
  1095. pattern = patterns->zero_format;
  1096. }
  1097. // c. Else if x > 0, then
  1098. else if (number > 0) {
  1099. // i. Let pattern be patterns.[[positivePattern]].
  1100. pattern = patterns->positive_format;
  1101. }
  1102. // d. Else,
  1103. else {
  1104. // i. Let pattern be patterns.[[negativePattern]].
  1105. pattern = patterns->negative_format;
  1106. }
  1107. break;
  1108. default:
  1109. VERIFY_NOT_REACHED();
  1110. }
  1111. // 16. Return pattern.
  1112. return pattern;
  1113. }
  1114. // 15.1.15 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1115. StringView get_notation_sub_pattern([[maybe_unused]] NumberFormat& number_format, [[maybe_unused]] int exponent)
  1116. {
  1117. // FIXME: Implement this.
  1118. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1119. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1120. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1121. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1122. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1123. // 6. Let notation be numberFormat.[[Notation]].
  1124. // 7. If notation is "scientific" or notation is "engineering", then
  1125. // a. Return notationSubPatterns.[[scientific]].
  1126. // 8. Else if exponent is not 0, then
  1127. // a. Assert: notation is "compact".
  1128. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1129. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1130. // d. Return compactPatterns.[[<exponent>]].
  1131. // 9. Else,
  1132. // a. Return "{number}".
  1133. return "{number}"sv;
  1134. }
  1135. // 15.1.16 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1136. int compute_exponent(NumberFormat& number_format, double number)
  1137. {
  1138. // 1. If x = 0, then
  1139. if (number == 0.0) {
  1140. // a. Return 0.
  1141. return 0;
  1142. }
  1143. // 2. If x < 0, then
  1144. if (number < 0) {
  1145. // a. Let x = -x.
  1146. number *= -1;
  1147. }
  1148. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1149. int magnitude = log10floor(number);
  1150. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1151. int exponent = compute_exponent_for_magniude(number_format, magnitude);
  1152. // 5. Let x be x × 10^(-exponent).
  1153. number *= pow(10, -exponent);
  1154. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1155. auto format_number_result = format_numeric_to_string(number_format, number);
  1156. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1157. if (format_number_result.rounded_number == 0) {
  1158. // a. Return exponent.
  1159. return exponent;
  1160. }
  1161. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1162. int new_magnitude = log10floor(format_number_result.rounded_number);
  1163. // 9. If newMagnitude is magnitude – exponent, then
  1164. if (new_magnitude == magnitude - exponent) {
  1165. // a. Return exponent.
  1166. return exponent;
  1167. }
  1168. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1169. return compute_exponent_for_magniude(number_format, magnitude + 1);
  1170. }
  1171. // 15.1.17 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1172. int compute_exponent_for_magniude(NumberFormat& number_format, int magnitude)
  1173. {
  1174. // 1. Let notation be numberFormat.[[Notation]].
  1175. switch (number_format.notation()) {
  1176. // 2. If notation is "standard", then
  1177. case NumberFormat::Notation::Standard:
  1178. // a. Return 0.
  1179. return 0;
  1180. // 3. Else if notation is "scientific", then
  1181. case NumberFormat::Notation::Scientific:
  1182. // a. Return magnitude.
  1183. return magnitude;
  1184. // 4. Else if notation is "engineering", then
  1185. case NumberFormat::Notation::Engineering: {
  1186. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1187. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1188. // b. Return thousands × 3.
  1189. return static_cast<int>(thousands) * 3;
  1190. }
  1191. // 5. Else,
  1192. case NumberFormat::Notation::Compact: {
  1193. // a. Assert: notation is "compact".
  1194. VERIFY(number_format.has_compact_display());
  1195. // 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.
  1196. // c. Return exponent.
  1197. Vector<Unicode::NumberFormat> format_rules;
  1198. if (number_format.style() == NumberFormat::Style::Currency)
  1199. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyShort);
  1200. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1201. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalLong);
  1202. else
  1203. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalShort);
  1204. Unicode::NumberFormat const* best_number_format = nullptr;
  1205. for (auto const& format_rule : format_rules) {
  1206. if (format_rule.magnitude > magnitude)
  1207. break;
  1208. best_number_format = &format_rule;
  1209. }
  1210. return best_number_format ? best_number_format->compact_scale : 0;
  1211. }
  1212. default:
  1213. VERIFY_NOT_REACHED();
  1214. }
  1215. }
  1216. }