NumberFormat.cpp 67 KB

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