NumberFormat.cpp 67 KB

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