NumberFormat.cpp 63 KB

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