NumberFormat.cpp 63 KB

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