NumberFormat.cpp 68 KB

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