NumberFormat.cpp 71 KB

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