NumberFormat.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  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.5.1 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  296. int currency_digits(StringView currency)
  297. {
  298. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  299. // unit value corresponding to the currency from the list; otherwise, return 2.
  300. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  301. return currency_code->minor_unit.value_or(2);
  302. return 2;
  303. }
  304. // 15.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  305. FormatResult format_numeric_to_string(GlobalObject& global_object, NumberFormatBase& intl_object, Value number)
  306. {
  307. // 1. If x < 0 or x is -0𝔽, let isNegative be true; else let isNegative be false.
  308. bool is_negative = is_less_than(number, 0) || number.is_negative_zero();
  309. // 2. If isNegative, then
  310. if (is_negative) {
  311. // a. Let x be -x.
  312. number = multiply(global_object, number, -1);
  313. }
  314. RawFormatResult result {};
  315. switch (intl_object.rounding_type()) {
  316. // 3. If intlObject.[[RoundingType]] is significantDigits, then
  317. case NumberFormatBase::RoundingType::SignificantDigits:
  318. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]]).
  319. result = to_raw_precision(global_object, number, intl_object.min_significant_digits(), intl_object.max_significant_digits());
  320. break;
  321. // 4. Else if intlObject.[[RoundingType]] is fractionDigits, then
  322. case NumberFormatBase::RoundingType::FractionDigits:
  323. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]]).
  324. result = to_raw_fixed(global_object, number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits());
  325. break;
  326. // 5. Else,
  327. case NumberFormatBase::RoundingType::CompactRounding:
  328. // a. Assert: intlObject.[[RoundingType]] is compactRounding.
  329. // b. Let result be ToRawPrecision(x, 1, 2).
  330. result = to_raw_precision(global_object, number, 1, 2);
  331. // c. If result.[[IntegerDigitsCount]] > 1, then
  332. if (result.digits > 1) {
  333. // i. Let result be ToRawFixed(x, 0, 0).
  334. result = to_raw_fixed(global_object, number, 0, 0);
  335. }
  336. break;
  337. default:
  338. VERIFY_NOT_REACHED();
  339. }
  340. // 6. Let x be result.[[RoundedNumber]].
  341. number = result.rounded_number;
  342. // 7. Let string be result.[[FormattedString]].
  343. auto string = move(result.formatted_string);
  344. // 8. Let int be result.[[IntegerDigitsCount]].
  345. int digits = result.digits;
  346. // 9. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  347. int min_integer = intl_object.min_integer_digits();
  348. // 10. If int < minInteger, then
  349. if (digits < min_integer) {
  350. // a. Let forwardZeros be the String consisting of minInteger–int occurrences of the character "0".
  351. auto forward_zeros = String::repeated('0', min_integer - digits);
  352. // b. Set string to the string-concatenation of forwardZeros and string.
  353. string = String::formatted("{}{}", forward_zeros, string);
  354. }
  355. // 11. If isNegative, then
  356. if (is_negative) {
  357. // a. Let x be -x.
  358. number = multiply(global_object, number, -1);
  359. }
  360. // 12. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  361. return { move(string), number };
  362. }
  363. // 15.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  364. Vector<PatternPartition> partition_number_pattern(GlobalObject& global_object, NumberFormat& number_format, Value number)
  365. {
  366. // 1. Let exponent be 0.
  367. int exponent = 0;
  368. String formatted_string;
  369. // 2. If x is NaN, then
  370. if (number.is_nan()) {
  371. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  372. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::NaN).value_or("NaN"sv);
  373. }
  374. // 3. Else if x is +∞, then
  375. else if (number.is_positive_infinity()) {
  376. // a. Let n be an ILD String value indicating positive infinity.
  377. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Infinity).value_or("infinity"sv);
  378. }
  379. // 4. Else if x is -∞, then
  380. else if (number.is_negative_infinity()) {
  381. // a. Let n be an ILD String value indicating negative infinity.
  382. // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
  383. // be inserted by the pattern returned from GetNumberFormatPattern.
  384. formatted_string = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Infinity).value_or("infinity"sv);
  385. }
  386. // 5. Else,
  387. else {
  388. // a. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  389. if (number_format.style() == NumberFormat::Style::Percent)
  390. number = multiply(global_object, number, 100);
  391. // b. Let exponent be ComputeExponent(numberFormat, x).
  392. exponent = compute_exponent(global_object, number_format, number);
  393. // c. Let x be x × 10^(-exponent).
  394. number = multiply_by_power(global_object, number, -exponent);
  395. // d. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  396. auto format_number_result = format_numeric_to_string(global_object, number_format, number);
  397. // e. Let n be formatNumberResult.[[FormattedString]].
  398. formatted_string = move(format_number_result.formatted_string);
  399. // f. Let x be formatNumberResult.[[RoundedNumber]].
  400. number = format_number_result.rounded_number;
  401. }
  402. Unicode::NumberFormat found_pattern {};
  403. // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
  404. auto pattern = get_number_format_pattern(number_format, number, found_pattern);
  405. if (!pattern.has_value())
  406. return {};
  407. // 7. Let result be a new empty List.
  408. Vector<PatternPartition> result;
  409. // 8. Let patternParts be PartitionPattern(pattern).
  410. auto pattern_parts = pattern->visit([](auto const& p) { return partition_pattern(p); });
  411. // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  412. for (auto& pattern_part : pattern_parts) {
  413. // a. Let p be patternPart.[[Type]].
  414. auto part = pattern_part.type;
  415. // b. If p is "literal", then
  416. if (part == "literal"sv) {
  417. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  418. result.append({ "literal"sv, move(pattern_part.value) });
  419. }
  420. // c. Else if p is equal to "number", then
  421. else if (part == "number"sv) {
  422. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  423. auto notation_sub_parts = partition_notation_sub_pattern(global_object, number_format, number, formatted_string, exponent);
  424. // ii. Append all elements of notationSubParts to result.
  425. result.extend(move(notation_sub_parts));
  426. }
  427. // d. Else if p is equal to "plusSign", then
  428. else if (part == "plusSign"sv) {
  429. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  430. auto plus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::PlusSign).value_or("+"sv);
  431. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  432. result.append({ "plusSign"sv, plus_sign_symbol });
  433. }
  434. // e. Else if p is equal to "minusSign", then
  435. else if (part == "minusSign"sv) {
  436. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  437. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::MinusSign).value_or("-"sv);
  438. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  439. result.append({ "minusSign"sv, minus_sign_symbol });
  440. }
  441. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  442. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  443. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  444. auto percent_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::PercentSign).value_or("%"sv);
  445. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  446. result.append({ "percentSign"sv, percent_sign_symbol });
  447. }
  448. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  449. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  450. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  451. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  452. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  453. VERIFY(identifier_index.has_value());
  454. // i. Let unit be numberFormat.[[Unit]].
  455. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  456. // 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.
  457. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  458. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  459. result.append({ "unit"sv, unit_identifier });
  460. }
  461. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  462. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  463. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  464. //
  465. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  466. // currency code during GetNumberFormatPattern so that we do not have to do currency
  467. // display / plurality lookups more than once.
  468. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  469. result.append({ "currency"sv, number_format.resolve_currency_display() });
  470. }
  471. // l. Else,
  472. else {
  473. // i. Let unknown be an ILND String based on x and p.
  474. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  475. // LibUnicode doesn't generate any "unknown" patterns.
  476. VERIFY_NOT_REACHED();
  477. }
  478. }
  479. // 10. Return result.
  480. return result;
  481. }
  482. static Vector<StringView> separate_integer_into_groups(Unicode::NumberGroupings const& grouping_sizes, StringView integer)
  483. {
  484. Utf8View utf8_integer { integer };
  485. if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
  486. return { integer };
  487. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  488. if (index < grouping_sizes.minimum_grouping_digits)
  489. return { integer };
  490. Vector<StringView> groups;
  491. auto add_group = [&](size_t index, size_t length) {
  492. groups.prepend(utf8_integer.unicode_substring_view(index, length).as_string());
  493. };
  494. add_group(index, grouping_sizes.primary_grouping_size);
  495. while (index > grouping_sizes.secondary_grouping_size) {
  496. index -= grouping_sizes.secondary_grouping_size;
  497. add_group(index, grouping_sizes.secondary_grouping_size);
  498. }
  499. if (index > 0)
  500. add_group(0, index);
  501. return groups;
  502. }
  503. // 15.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  504. Vector<PatternPartition> partition_notation_sub_pattern(GlobalObject& global_object, NumberFormat& number_format, Value number, String formatted_string, int exponent)
  505. {
  506. // 1. Let result be a new empty List.
  507. Vector<PatternPartition> result;
  508. auto grouping_sizes = Unicode::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  509. if (!grouping_sizes.has_value())
  510. return {};
  511. // 2. If x is NaN, then
  512. if (number.is_nan()) {
  513. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  514. result.append({ "nan"sv, move(formatted_string) });
  515. }
  516. // 3. Else if x is a non-finite Number, then
  517. else if (number.is_number() && !number.is_finite_number()) {
  518. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  519. result.append({ "infinity"sv, move(formatted_string) });
  520. }
  521. // 4. Else,
  522. else {
  523. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  524. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  525. if (!notation_sub_pattern.has_value())
  526. return {};
  527. // b. Let patternParts be PartitionPattern(notationSubPattern).
  528. auto pattern_parts = partition_pattern(*notation_sub_pattern);
  529. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  530. for (auto& pattern_part : pattern_parts) {
  531. // i. Let p be patternPart.[[Type]].
  532. auto part = pattern_part.type;
  533. // ii. If p is "literal", then
  534. if (part == "literal"sv) {
  535. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  536. result.append({ "literal"sv, move(pattern_part.value) });
  537. }
  538. // iii. Else if p is equal to "number", then
  539. else if (part == "number"sv) {
  540. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 12 below, then
  541. // 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 12.
  542. // b. Replace each digit in n with the value of digits[digit].
  543. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  544. formatted_string = Unicode::replace_digits_for_number_system(number_format.numbering_system(), formatted_string);
  545. // 3. Let decimalSepIndex be ! StringIndexOf(n, ".", 0).
  546. auto decimal_sep_index = formatted_string.find('.');
  547. StringView integer;
  548. Optional<StringView> fraction;
  549. // 4. If decimalSepIndex > 0, then
  550. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  551. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  552. integer = formatted_string.substring_view(0, *decimal_sep_index);
  553. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  554. fraction = formatted_string.substring_view(*decimal_sep_index + 1);
  555. }
  556. // 5. Else,
  557. else {
  558. // a. Let integer be n.
  559. integer = formatted_string;
  560. // b. Let fraction be undefined.
  561. }
  562. bool use_grouping = number_format.use_grouping();
  563. // FIXME: The spec doesn't indicate this, but grouping should be disabled for numbers less than 10,000 when the notation is compact.
  564. // This is addressed in Intl.NumberFormat V3 with the "min2" [[UseGrouping]] option. However, test262 explicitly expects this
  565. // behavior in the "de-DE" locale tests, because this is how ICU (and therefore V8, SpiderMoney, etc.) has always behaved.
  566. //
  567. // So, in locales "de-*", we must have:
  568. // Intl.NumberFormat("de", {notation: "compact"}).format(1234) === "1234"
  569. // Intl.NumberFormat("de", {notation: "compact"}).format(12345) === "12.345"
  570. // Intl.NumberFormat("de").format(1234) === "1.234"
  571. // Intl.NumberFormat("de").format(12345) === "12.345"
  572. //
  573. // See: https://github.com/tc39/proposal-intl-numberformat-v3/issues/3
  574. if (number_format.has_compact_format())
  575. use_grouping = is_greater_than_or_equal(number, 10'000);
  576. // 6. If the numberFormat.[[UseGrouping]] is true, then
  577. if (use_grouping) {
  578. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  579. auto group_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Group).value_or(","sv);
  580. // 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.
  581. auto groups = separate_integer_into_groups(*grouping_sizes, integer);
  582. // c. Assert: The number of elements in groups List is greater than 0.
  583. VERIFY(!groups.is_empty());
  584. // d. Repeat, while groups List is not empty,
  585. while (!groups.is_empty()) {
  586. // i. Remove the first element from groups and let integerGroup be the value of that element.
  587. auto integer_group = groups.take_first();
  588. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  589. result.append({ "integer"sv, integer_group });
  590. // iii. If groups List is not empty, then
  591. if (!groups.is_empty()) {
  592. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  593. result.append({ "group"sv, group_sep_symbol });
  594. }
  595. }
  596. }
  597. // 7. Else,
  598. else {
  599. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  600. result.append({ "integer"sv, integer });
  601. }
  602. // 8. If fraction is not undefined, then
  603. if (fraction.has_value()) {
  604. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  605. auto decimal_sep_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Decimal).value_or("."sv);
  606. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  607. result.append({ "decimal"sv, decimal_sep_symbol });
  608. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  609. result.append({ "fraction"sv, fraction.release_value() });
  610. }
  611. }
  612. // iv. Else if p is equal to "compactSymbol", then
  613. // v. Else if p is equal to "compactName", then
  614. else if (part.starts_with("compactIdentifier:"sv)) {
  615. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  616. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  617. VERIFY(identifier_index.has_value());
  618. // 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.
  619. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  620. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  621. result.append({ "compact"sv, compact_identifier });
  622. }
  623. // vi. Else if p is equal to "scientificSeparator", then
  624. else if (part == "scientificSeparator"sv) {
  625. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  626. auto scientific_separator = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::Exponential).value_or("E"sv);
  627. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  628. result.append({ "exponentSeparator"sv, scientific_separator });
  629. }
  630. // vii. Else if p is equal to "scientificExponent", then
  631. else if (part == "scientificExponent"sv) {
  632. // 1. If exponent < 0, then
  633. if (exponent < 0) {
  634. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  635. auto minus_sign_symbol = Unicode::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), Unicode::NumericSymbol::MinusSign).value_or("-"sv);
  636. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  637. result.append({ "exponentMinusSign"sv, minus_sign_symbol });
  638. // c. Let exponent be -exponent.
  639. exponent *= -1;
  640. }
  641. // 2. Let exponentResult be ToRawFixed(exponent, 1, 0, 0).
  642. // Note: See the implementation of ToRawFixed for why we do not pass the 1.
  643. auto exponent_result = to_raw_fixed(global_object, Value(exponent), 0, 0);
  644. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  645. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  646. exponent_result.formatted_string = Unicode::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string);
  647. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  648. result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
  649. }
  650. // viii. Else,
  651. else {
  652. // 1. Let unknown be an ILND String based on x and p.
  653. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  654. // LibUnicode doesn't generate any "unknown" patterns.
  655. VERIFY_NOT_REACHED();
  656. }
  657. }
  658. }
  659. // 5. Return result.
  660. return result;
  661. }
  662. // 15.5.6 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  663. String format_numeric(GlobalObject& global_object, NumberFormat& number_format, Value number)
  664. {
  665. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  666. // Note: Our implementation of PartitionNumberPattern does not throw.
  667. auto parts = partition_number_pattern(global_object, number_format, number);
  668. // 2. Let result be the empty String.
  669. StringBuilder result;
  670. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  671. for (auto& part : parts) {
  672. // a. Set result to the string-concatenation of result and part.[[Value]].
  673. result.append(move(part.value));
  674. }
  675. // 4. Return result.
  676. return result.build();
  677. }
  678. // 15.5.7 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  679. Array* format_numeric_to_parts(GlobalObject& global_object, NumberFormat& number_format, Value number)
  680. {
  681. auto& vm = global_object.vm();
  682. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  683. // Note: Our implementation of PartitionNumberPattern does not throw.
  684. auto parts = partition_number_pattern(global_object, number_format, number);
  685. // 2. Let result be ArrayCreate(0).
  686. auto* result = MUST(Array::create(global_object, 0));
  687. // 3. Let n be 0.
  688. size_t n = 0;
  689. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  690. for (auto& part : parts) {
  691. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  692. auto* object = Object::create(global_object, global_object.object_prototype());
  693. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  694. MUST(object->create_data_property_or_throw(vm.names.type, js_string(vm, part.type)));
  695. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  696. MUST(object->create_data_property_or_throw(vm.names.value, js_string(vm, move(part.value))));
  697. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  698. MUST(result->create_data_property_or_throw(n, object));
  699. // e. Increment n by 1.
  700. ++n;
  701. }
  702. // 5. Return result.
  703. return result;
  704. }
  705. static String cut_trailing_zeroes(StringView string, int cut)
  706. {
  707. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  708. // Repeat, while cut > 0 and the last character of m is "0",
  709. while ((cut > 0) && string.ends_with('0')) {
  710. // Remove the last character from m.
  711. string = string.substring_view(0, string.length() - 1);
  712. // Decrease cut by 1.
  713. --cut;
  714. }
  715. // If the last character of m is ".", then
  716. if (string.ends_with('.')) {
  717. // Remove the last character from m.
  718. string = string.substring_view(0, string.length() - 1);
  719. }
  720. return string.to_string();
  721. }
  722. // 15.5.8 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  723. RawFormatResult to_raw_precision(GlobalObject& global_object, Value number, int min_precision, int max_precision)
  724. {
  725. RawFormatResult result {};
  726. // 1. Set x to ℝ(x).
  727. // 2. Let p be maxPrecision.
  728. int precision = max_precision;
  729. int exponent = 0;
  730. // 3. If x = 0, then
  731. if (is_zero(number)) {
  732. // a. Let m be the String consisting of p occurrences of the character "0".
  733. result.formatted_string = String::repeated('0', precision);
  734. // b. Let e be 0.
  735. exponent = 0;
  736. // c. Let xFinal be 0.
  737. result.rounded_number = Value(0);
  738. }
  739. // 4. Else,
  740. else {
  741. // FIXME: The result of these steps isn't entirely accurate for large values of 'p' (which
  742. // defaults to 21, resulting in numbers on the order of 10^21). Either AK::format or
  743. // our Number::toString AO (double_to_string in Value.cpp) will need to be improved
  744. // to produce more accurate results.
  745. // 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.
  746. // If there are two such sets of e and n, pick the e and n for which n × 10^(e–p+1) is larger.
  747. exponent = log10floor(number);
  748. Value n;
  749. if (number.is_number()) {
  750. n = rounded(divide_by_power(global_object, number, exponent - precision + 1));
  751. } else {
  752. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  753. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  754. n = divide_by_power(global_object, number, exponent - precision);
  755. // FIXME: Can we do this without string conversion?
  756. auto digits = n.as_bigint().big_integer().to_base(10);
  757. auto digit = digits.substring_view(digits.length() - 1);
  758. n = divide(global_object, n, 10);
  759. if (digit.to_uint().value() >= 5)
  760. n = js_bigint(global_object.vm(), n.as_bigint().big_integer().plus(Crypto::SignedBigInteger::create_from(1)));
  761. }
  762. // b. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  763. result.formatted_string = number_to_string(n);
  764. // c. Let xFinal be n × 10^(e–p+1).
  765. result.rounded_number = multiply_by_power(global_object, n, exponent - precision + 1);
  766. }
  767. // 5. If e ≥ p–1, then
  768. if (exponent >= (precision - 1)) {
  769. // a. Let m be the string-concatenation of m and e–p+1 occurrences of the character "0".
  770. result.formatted_string = String::formatted(
  771. "{}{}",
  772. result.formatted_string,
  773. String::repeated('0', exponent - precision + 1));
  774. // b. Let int be e+1.
  775. result.digits = exponent + 1;
  776. }
  777. // 6. Else if e ≥ 0, then
  778. else if (exponent >= 0) {
  779. // 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.
  780. result.formatted_string = String::formatted(
  781. "{}.{}",
  782. result.formatted_string.substring_view(0, exponent + 1),
  783. result.formatted_string.substring_view(exponent + 1));
  784. // b. Let int be e+1.
  785. result.digits = exponent + 1;
  786. }
  787. // 7. Else,
  788. else {
  789. // a. Assert: e < 0.
  790. // b. Let m be the string-concatenation of the String value "0.", –(e+1) occurrences of the character "0", and m.
  791. result.formatted_string = String::formatted(
  792. "0.{}{}",
  793. String::repeated('0', -1 * (exponent + 1)),
  794. result.formatted_string);
  795. // c. Let int be 1.
  796. result.digits = 1;
  797. }
  798. // 8. If m contains the character ".", and maxPrecision > minPrecision, then
  799. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  800. // a. Let cut be maxPrecision – minPrecision.
  801. int cut = max_precision - min_precision;
  802. // Steps 8b-8c are implemented by cut_trailing_zeroes.
  803. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  804. }
  805. // 9. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  806. return result;
  807. }
  808. // 15.5.9 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  809. // NOTE: The spec has a mistake here. The minInteger parameter is unused and is not provided by FormatNumericToString.
  810. RawFormatResult to_raw_fixed(GlobalObject& global_object, Value number, int min_fraction, int max_fraction)
  811. {
  812. RawFormatResult result {};
  813. // 1. Set x to ℝ(x).
  814. // 2. Let f be maxFraction.
  815. int fraction = max_fraction;
  816. // 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.
  817. auto n = rounded(multiply_by_power(global_object, number, fraction));
  818. // 4. Let xFinal be n / 10^f.
  819. result.rounded_number = divide_by_power(global_object, n, fraction);
  820. // 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).
  821. result.formatted_string = is_zero(n) ? String("0"sv) : number_to_string(n);
  822. // 6. If f ≠ 0, then
  823. if (fraction != 0) {
  824. // a. Let k be the number of characters in m.
  825. auto decimals = result.formatted_string.length();
  826. // b. If k ≤ f, then
  827. if (decimals <= static_cast<size_t>(fraction)) {
  828. // i. Let z be the String value consisting of f+1–k occurrences of the character "0".
  829. auto zeroes = String::repeated('0', fraction + 1 - decimals);
  830. // ii. Let m be the string-concatenation of z and m.
  831. result.formatted_string = String::formatted("{}{}", zeroes, result.formatted_string);
  832. // iii. Let k be f+1.
  833. decimals = fraction + 1;
  834. }
  835. // c. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
  836. auto a = result.formatted_string.substring_view(0, decimals - fraction);
  837. auto b = result.formatted_string.substring_view(decimals - fraction, fraction);
  838. // d. Let m be the string-concatenation of a, ".", and b.
  839. result.formatted_string = String::formatted("{}.{}", a, b);
  840. // e. Let int be the number of characters in a.
  841. result.digits = a.length();
  842. }
  843. // 7. Else, let int be the number of characters in m.
  844. else {
  845. result.digits = result.formatted_string.length();
  846. }
  847. // 8. Let cut be maxFraction – minFraction.
  848. int cut = max_fraction - min_fraction;
  849. // Steps 9-10 are implemented by cut_trailing_zeroes.
  850. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  851. // 11. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int }.
  852. return result;
  853. }
  854. // 15.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  855. Optional<Variant<StringView, String>> get_number_format_pattern(NumberFormat& number_format, Value number, Unicode::NumberFormat& found_pattern)
  856. {
  857. auto as_number = [&]() {
  858. if (number.is_number())
  859. return number.as_double();
  860. // FIXME: This should be okay for now as our naive Unicode::select_pattern_with_plurality implementation
  861. // checks against just a few specific small values. But revisit this if precision becomes a concern.
  862. return number.as_bigint().big_integer().to_double();
  863. };
  864. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  865. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  866. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  867. // 4. Let patterns be dataLocaleData.[[patterns]].
  868. // 5. Assert: patterns is a Record (see 15.3.3).
  869. Optional<Unicode::NumberFormat> patterns;
  870. // 6. Let style be numberFormat.[[Style]].
  871. switch (number_format.style()) {
  872. // 7. If style is "percent", then
  873. case NumberFormat::Style::Percent:
  874. // a. Let patterns be patterns.[[percent]].
  875. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Percent);
  876. break;
  877. // 8. Else if style is "unit", then
  878. case NumberFormat::Style::Unit: {
  879. // a. Let unit be numberFormat.[[Unit]].
  880. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  881. // c. Let patterns be patterns.[[unit]].
  882. // d. If patterns doesn't have a field [[<unit>]], then
  883. // i. Let unit be "fallback".
  884. // e. Let patterns be patterns.[[<unit>]].
  885. // f. Let patterns be patterns.[[<unitDisplay>]].
  886. auto formats = Unicode::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display());
  887. patterns = Unicode::select_pattern_with_plurality(formats, as_number());
  888. break;
  889. }
  890. // 9. Else if style is "currency", then
  891. case NumberFormat::Style::Currency:
  892. // a. Let currency be numberFormat.[[Currency]].
  893. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  894. // c. Let currencySign be numberFormat.[[CurrencySign]].
  895. // d. Let patterns be patterns.[[currency]].
  896. // e. If patterns doesn't have a field [[<currency>]], then
  897. // i. Let currency be "fallback".
  898. // f. Let patterns be patterns.[[<currency>]].
  899. // g. Let patterns be patterns.[[<currencyDisplay>]].
  900. // h. Let patterns be patterns.[[<currencySign>]].
  901. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  902. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  903. auto formats = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyUnit);
  904. auto maybe_patterns = Unicode::select_pattern_with_plurality(formats, as_number());
  905. if (maybe_patterns.has_value()) {
  906. patterns = maybe_patterns.release_value();
  907. break;
  908. }
  909. }
  910. switch (number_format.currency_sign()) {
  911. case NumberFormat::CurrencySign::Standard:
  912. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Currency);
  913. break;
  914. case NumberFormat::CurrencySign::Accounting:
  915. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Accounting);
  916. break;
  917. }
  918. break;
  919. // 10. Else,
  920. case NumberFormat::Style::Decimal:
  921. // a. Assert: style is "decimal".
  922. // b. Let patterns be patterns.[[decimal]].
  923. patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Decimal);
  924. break;
  925. default:
  926. VERIFY_NOT_REACHED();
  927. }
  928. if (!patterns.has_value())
  929. return {};
  930. StringView pattern;
  931. bool is_positive_zero = number.is_positive_zero() || (number.is_bigint() && is_zero(number));
  932. bool is_negative_zero = number.is_negative_zero();
  933. bool is_nan = number.is_nan();
  934. // 11. Let signDisplay be numberFormat.[[SignDisplay]].
  935. switch (number_format.sign_display()) {
  936. // 12. If signDisplay is "never", then
  937. case NumberFormat::SignDisplay::Never:
  938. // a. Let pattern be patterns.[[zeroPattern]].
  939. pattern = patterns->zero_format;
  940. break;
  941. // 13. Else if signDisplay is "auto", then
  942. case NumberFormat::SignDisplay::Auto:
  943. // a. If x is 0 or x > 0 or x is NaN, then
  944. if (is_positive_zero || is_greater_than(number, 0) || is_nan) {
  945. // i. Let pattern be patterns.[[zeroPattern]].
  946. pattern = patterns->zero_format;
  947. }
  948. // b. Else,
  949. else {
  950. // i. Let pattern be patterns.[[negativePattern]].
  951. pattern = patterns->negative_format;
  952. }
  953. break;
  954. // 14. Else if signDisplay is "always", then
  955. case NumberFormat::SignDisplay::Always:
  956. // a. If x is 0 or x > 0 or x is NaN, then
  957. if (is_positive_zero || is_greater_than(number, 0) || is_nan) {
  958. // i. Let pattern be patterns.[[positivePattern]].
  959. pattern = patterns->positive_format;
  960. }
  961. // b. Else,
  962. else {
  963. // i. Let pattern be patterns.[[negativePattern]].
  964. pattern = patterns->negative_format;
  965. }
  966. break;
  967. // 15. Else,
  968. case NumberFormat::SignDisplay::ExceptZero:
  969. // a. Assert: signDisplay is "exceptZero".
  970. // b. If x is 0 or x is -0 or x is NaN, then
  971. if (is_positive_zero || is_negative_zero || is_nan) {
  972. // i. Let pattern be patterns.[[zeroPattern]].
  973. pattern = patterns->zero_format;
  974. }
  975. // c. Else if x > 0, then
  976. else if (is_greater_than(number, 0)) {
  977. // i. Let pattern be patterns.[[positivePattern]].
  978. pattern = patterns->positive_format;
  979. }
  980. // d. Else,
  981. else {
  982. // i. Let pattern be patterns.[[negativePattern]].
  983. pattern = patterns->negative_format;
  984. }
  985. break;
  986. default:
  987. VERIFY_NOT_REACHED();
  988. }
  989. found_pattern = patterns.release_value();
  990. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  991. // we might need to mutate the format pattern to inject a space between the currency display and
  992. // the currency number.
  993. if (number_format.style() == NumberFormat::Style::Currency) {
  994. auto modified_pattern = Unicode::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern);
  995. if (modified_pattern.has_value())
  996. return modified_pattern.release_value();
  997. }
  998. // 16. Return pattern.
  999. return pattern;
  1000. }
  1001. // 15.5.12 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1002. Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
  1003. {
  1004. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1005. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1006. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1007. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1008. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1009. // 6. Let notation be numberFormat.[[Notation]].
  1010. auto notation = number_format.notation();
  1011. // 7. If notation is "scientific" or notation is "engineering", then
  1012. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1013. // a. Return notationSubPatterns.[[scientific]].
  1014. auto notation_sub_patterns = Unicode::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), Unicode::StandardNumberFormatType::Scientific);
  1015. if (!notation_sub_patterns.has_value())
  1016. return {};
  1017. return notation_sub_patterns->zero_format;
  1018. }
  1019. // 8. Else if exponent is not 0, then
  1020. else if (exponent != 0) {
  1021. // a. Assert: notation is "compact".
  1022. VERIFY(notation == NumberFormat::Notation::Compact);
  1023. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1024. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1025. // d. Return compactPatterns.[[<exponent>]].
  1026. if (number_format.has_compact_format())
  1027. return number_format.compact_format().zero_format;
  1028. }
  1029. // 9. Else,
  1030. // a. Return "{number}".
  1031. return "{number}"sv;
  1032. }
  1033. // 15.5.13 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1034. int compute_exponent(GlobalObject& global_object, NumberFormat& number_format, Value number)
  1035. {
  1036. // 1. If x = 0, then
  1037. if (is_zero(number)) {
  1038. // a. Return 0.
  1039. return 0;
  1040. }
  1041. // 2. If x < 0, then
  1042. if (is_less_than(number, 0)) {
  1043. // a. Let x = -x.
  1044. number = multiply(global_object, number, -1);
  1045. }
  1046. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1047. int magnitude = log10floor(number);
  1048. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1049. int exponent = compute_exponent_for_magnitude(number_format, magnitude);
  1050. // 5. Let x be x × 10^(-exponent).
  1051. number = multiply_by_power(global_object, number, -exponent);
  1052. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1053. auto format_number_result = format_numeric_to_string(global_object, number_format, number);
  1054. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1055. if (is_zero(format_number_result.rounded_number)) {
  1056. // a. Return exponent.
  1057. return exponent;
  1058. }
  1059. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1060. int new_magnitude = log10floor(format_number_result.rounded_number);
  1061. // 9. If newMagnitude is magnitude – exponent, then
  1062. if (new_magnitude == magnitude - exponent) {
  1063. // a. Return exponent.
  1064. return exponent;
  1065. }
  1066. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1067. return compute_exponent_for_magnitude(number_format, magnitude + 1);
  1068. }
  1069. // 15.5.14 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1070. int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
  1071. {
  1072. // 1. Let notation be numberFormat.[[Notation]].
  1073. switch (number_format.notation()) {
  1074. // 2. If notation is "standard", then
  1075. case NumberFormat::Notation::Standard:
  1076. // a. Return 0.
  1077. return 0;
  1078. // 3. Else if notation is "scientific", then
  1079. case NumberFormat::Notation::Scientific:
  1080. // a. Return magnitude.
  1081. return magnitude;
  1082. // 4. Else if notation is "engineering", then
  1083. case NumberFormat::Notation::Engineering: {
  1084. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1085. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1086. // b. Return thousands × 3.
  1087. return static_cast<int>(thousands) * 3;
  1088. }
  1089. // 5. Else,
  1090. case NumberFormat::Notation::Compact: {
  1091. // a. Assert: notation is "compact".
  1092. VERIFY(number_format.has_compact_display());
  1093. // 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.
  1094. // c. Return exponent.
  1095. Vector<Unicode::NumberFormat> format_rules;
  1096. if (number_format.style() == NumberFormat::Style::Currency)
  1097. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::CurrencyShort);
  1098. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1099. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalLong);
  1100. else
  1101. format_rules = Unicode::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), Unicode::CompactNumberFormatType::DecimalShort);
  1102. Unicode::NumberFormat const* best_number_format = nullptr;
  1103. for (auto const& format_rule : format_rules) {
  1104. if (format_rule.magnitude > magnitude)
  1105. break;
  1106. best_number_format = &format_rule;
  1107. }
  1108. if (best_number_format == nullptr)
  1109. return 0;
  1110. number_format.set_compact_format(*best_number_format);
  1111. return best_number_format->exponent;
  1112. }
  1113. default:
  1114. VERIFY_NOT_REACHED();
  1115. }
  1116. }
  1117. }