NumberFormat.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Utf8View.h>
  9. #include <LibCrypto/BigInt/SignedBigInteger.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/BigInt.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/Intl/NumberFormat.h>
  15. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  16. #include <LibJS/Runtime/Intl/PluralRules.h>
  17. #include <LibUnicode/CurrencyCode.h>
  18. #include <math.h>
  19. #include <stdlib.h>
  20. namespace JS::Intl {
  21. NumberFormatBase::NumberFormatBase(Object& prototype)
  22. : Object(ConstructWithPrototypeTag::Tag, prototype)
  23. {
  24. }
  25. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  26. NumberFormat::NumberFormat(Object& prototype)
  27. : NumberFormatBase(prototype)
  28. {
  29. }
  30. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. if (m_bound_format)
  34. visitor.visit(m_bound_format);
  35. }
  36. void NumberFormat::set_style(StringView style)
  37. {
  38. if (style == "decimal"sv)
  39. m_style = Style::Decimal;
  40. else if (style == "percent"sv)
  41. m_style = Style::Percent;
  42. else if (style == "currency"sv)
  43. m_style = Style::Currency;
  44. else if (style == "unit"sv)
  45. m_style = Style::Unit;
  46. else
  47. VERIFY_NOT_REACHED();
  48. }
  49. StringView NumberFormat::style_string() const
  50. {
  51. switch (m_style) {
  52. case Style::Decimal:
  53. return "decimal"sv;
  54. case Style::Percent:
  55. return "percent"sv;
  56. case Style::Currency:
  57. return "currency"sv;
  58. case Style::Unit:
  59. return "unit"sv;
  60. default:
  61. VERIFY_NOT_REACHED();
  62. }
  63. }
  64. void NumberFormat::set_currency_display(StringView currency_display)
  65. {
  66. m_resolved_currency_display.clear();
  67. if (currency_display == "code"sv)
  68. m_currency_display = CurrencyDisplay::Code;
  69. else if (currency_display == "symbol"sv)
  70. m_currency_display = CurrencyDisplay::Symbol;
  71. else if (currency_display == "narrowSymbol"sv)
  72. m_currency_display = CurrencyDisplay::NarrowSymbol;
  73. else if (currency_display == "name"sv)
  74. m_currency_display = CurrencyDisplay::Name;
  75. else
  76. VERIFY_NOT_REACHED();
  77. }
  78. StringView NumberFormat::resolve_currency_display()
  79. {
  80. if (m_resolved_currency_display.has_value())
  81. return *m_resolved_currency_display;
  82. switch (currency_display()) {
  83. case NumberFormat::CurrencyDisplay::Code:
  84. m_resolved_currency_display = currency();
  85. break;
  86. case NumberFormat::CurrencyDisplay::Symbol:
  87. m_resolved_currency_display = ::Locale::get_locale_short_currency_mapping(data_locale(), currency());
  88. break;
  89. case NumberFormat::CurrencyDisplay::NarrowSymbol:
  90. m_resolved_currency_display = ::Locale::get_locale_narrow_currency_mapping(data_locale(), currency());
  91. break;
  92. case NumberFormat::CurrencyDisplay::Name:
  93. m_resolved_currency_display = ::Locale::get_locale_numeric_currency_mapping(data_locale(), currency());
  94. break;
  95. default:
  96. VERIFY_NOT_REACHED();
  97. }
  98. if (!m_resolved_currency_display.has_value())
  99. m_resolved_currency_display = currency();
  100. return *m_resolved_currency_display;
  101. }
  102. StringView NumberFormat::currency_display_string() const
  103. {
  104. VERIFY(m_currency_display.has_value());
  105. switch (*m_currency_display) {
  106. case CurrencyDisplay::Code:
  107. return "code"sv;
  108. case CurrencyDisplay::Symbol:
  109. return "symbol"sv;
  110. case CurrencyDisplay::NarrowSymbol:
  111. return "narrowSymbol"sv;
  112. case CurrencyDisplay::Name:
  113. return "name"sv;
  114. default:
  115. VERIFY_NOT_REACHED();
  116. }
  117. }
  118. void NumberFormat::set_currency_sign(StringView currency_sign)
  119. {
  120. if (currency_sign == "standard"sv)
  121. m_currency_sign = CurrencySign::Standard;
  122. else if (currency_sign == "accounting"sv)
  123. m_currency_sign = CurrencySign::Accounting;
  124. else
  125. VERIFY_NOT_REACHED();
  126. }
  127. StringView NumberFormat::currency_sign_string() const
  128. {
  129. VERIFY(m_currency_sign.has_value());
  130. switch (*m_currency_sign) {
  131. case CurrencySign::Standard:
  132. return "standard"sv;
  133. case CurrencySign::Accounting:
  134. return "accounting"sv;
  135. default:
  136. VERIFY_NOT_REACHED();
  137. }
  138. }
  139. StringView NumberFormatBase::rounding_type_string() const
  140. {
  141. switch (m_rounding_type) {
  142. case RoundingType::SignificantDigits:
  143. return "significantDigits"sv;
  144. case RoundingType::FractionDigits:
  145. return "fractionDigits"sv;
  146. case RoundingType::MorePrecision:
  147. return "morePrecision"sv;
  148. case RoundingType::LessPrecision:
  149. return "lessPrecision"sv;
  150. default:
  151. VERIFY_NOT_REACHED();
  152. }
  153. }
  154. StringView NumberFormatBase::computed_rounding_priority_string() const
  155. {
  156. switch (m_computed_rounding_priority) {
  157. case ComputedRoundingPriority::Auto:
  158. return "auto"sv;
  159. case ComputedRoundingPriority::MorePrecision:
  160. return "morePrecision"sv;
  161. case ComputedRoundingPriority::LessPrecision:
  162. return "lessPrecision"sv;
  163. default:
  164. VERIFY_NOT_REACHED();
  165. }
  166. }
  167. StringView NumberFormatBase::rounding_mode_string() const
  168. {
  169. switch (m_rounding_mode) {
  170. case RoundingMode::Ceil:
  171. return "ceil"sv;
  172. case RoundingMode::Expand:
  173. return "expand"sv;
  174. case RoundingMode::Floor:
  175. return "floor"sv;
  176. case RoundingMode::HalfCeil:
  177. return "halfCeil"sv;
  178. case RoundingMode::HalfEven:
  179. return "halfEven"sv;
  180. case RoundingMode::HalfExpand:
  181. return "halfExpand"sv;
  182. case RoundingMode::HalfFloor:
  183. return "halfFloor"sv;
  184. case RoundingMode::HalfTrunc:
  185. return "halfTrunc"sv;
  186. case RoundingMode::Trunc:
  187. return "trunc"sv;
  188. default:
  189. VERIFY_NOT_REACHED();
  190. }
  191. }
  192. void NumberFormatBase::set_rounding_mode(StringView rounding_mode)
  193. {
  194. if (rounding_mode == "ceil"sv)
  195. m_rounding_mode = RoundingMode::Ceil;
  196. else if (rounding_mode == "expand"sv)
  197. m_rounding_mode = RoundingMode::Expand;
  198. else if (rounding_mode == "floor"sv)
  199. m_rounding_mode = RoundingMode::Floor;
  200. else if (rounding_mode == "halfCeil"sv)
  201. m_rounding_mode = RoundingMode::HalfCeil;
  202. else if (rounding_mode == "halfEven"sv)
  203. m_rounding_mode = RoundingMode::HalfEven;
  204. else if (rounding_mode == "halfExpand"sv)
  205. m_rounding_mode = RoundingMode::HalfExpand;
  206. else if (rounding_mode == "halfFloor"sv)
  207. m_rounding_mode = RoundingMode::HalfFloor;
  208. else if (rounding_mode == "halfTrunc"sv)
  209. m_rounding_mode = RoundingMode::HalfTrunc;
  210. else if (rounding_mode == "trunc"sv)
  211. m_rounding_mode = RoundingMode::Trunc;
  212. else
  213. VERIFY_NOT_REACHED();
  214. }
  215. StringView NumberFormatBase::trailing_zero_display_string() const
  216. {
  217. switch (m_trailing_zero_display) {
  218. case TrailingZeroDisplay::Auto:
  219. return "auto"sv;
  220. case TrailingZeroDisplay::StripIfInteger:
  221. return "stripIfInteger"sv;
  222. default:
  223. VERIFY_NOT_REACHED();
  224. }
  225. }
  226. void NumberFormatBase::set_trailing_zero_display(StringView trailing_zero_display)
  227. {
  228. if (trailing_zero_display == "auto"sv)
  229. m_trailing_zero_display = TrailingZeroDisplay::Auto;
  230. else if (trailing_zero_display == "stripIfInteger"sv)
  231. m_trailing_zero_display = TrailingZeroDisplay::StripIfInteger;
  232. else
  233. VERIFY_NOT_REACHED();
  234. }
  235. Value NumberFormat::use_grouping_to_value(VM& vm) const
  236. {
  237. switch (m_use_grouping) {
  238. case UseGrouping::Always:
  239. return PrimitiveString::create(vm, "always"_string);
  240. case UseGrouping::Auto:
  241. return PrimitiveString::create(vm, "auto"_string);
  242. case UseGrouping::Min2:
  243. return PrimitiveString::create(vm, "min2"_string);
  244. case UseGrouping::False:
  245. return Value(false);
  246. default:
  247. VERIFY_NOT_REACHED();
  248. }
  249. }
  250. void NumberFormat::set_use_grouping(StringOrBoolean const& use_grouping)
  251. {
  252. use_grouping.visit(
  253. [this](StringView grouping) {
  254. if (grouping == "always"sv)
  255. m_use_grouping = UseGrouping::Always;
  256. else if (grouping == "auto"sv)
  257. m_use_grouping = UseGrouping::Auto;
  258. else if (grouping == "min2"sv)
  259. m_use_grouping = UseGrouping::Min2;
  260. else
  261. VERIFY_NOT_REACHED();
  262. },
  263. [this](bool grouping) {
  264. VERIFY(!grouping);
  265. m_use_grouping = UseGrouping::False;
  266. });
  267. }
  268. void NumberFormat::set_notation(StringView notation)
  269. {
  270. if (notation == "standard"sv)
  271. m_notation = Notation::Standard;
  272. else if (notation == "scientific"sv)
  273. m_notation = Notation::Scientific;
  274. else if (notation == "engineering"sv)
  275. m_notation = Notation::Engineering;
  276. else if (notation == "compact"sv)
  277. m_notation = Notation::Compact;
  278. else
  279. VERIFY_NOT_REACHED();
  280. }
  281. StringView NumberFormat::notation_string() const
  282. {
  283. switch (m_notation) {
  284. case Notation::Standard:
  285. return "standard"sv;
  286. case Notation::Scientific:
  287. return "scientific"sv;
  288. case Notation::Engineering:
  289. return "engineering"sv;
  290. case Notation::Compact:
  291. return "compact"sv;
  292. default:
  293. VERIFY_NOT_REACHED();
  294. }
  295. }
  296. void NumberFormat::set_compact_display(StringView compact_display)
  297. {
  298. if (compact_display == "short"sv)
  299. m_compact_display = CompactDisplay::Short;
  300. else if (compact_display == "long"sv)
  301. m_compact_display = CompactDisplay::Long;
  302. else
  303. VERIFY_NOT_REACHED();
  304. }
  305. StringView NumberFormat::compact_display_string() const
  306. {
  307. VERIFY(m_compact_display.has_value());
  308. switch (*m_compact_display) {
  309. case CompactDisplay::Short:
  310. return "short"sv;
  311. case CompactDisplay::Long:
  312. return "long"sv;
  313. default:
  314. VERIFY_NOT_REACHED();
  315. }
  316. }
  317. void NumberFormat::set_sign_display(StringView sign_display)
  318. {
  319. if (sign_display == "auto"sv)
  320. m_sign_display = SignDisplay::Auto;
  321. else if (sign_display == "never"sv)
  322. m_sign_display = SignDisplay::Never;
  323. else if (sign_display == "always"sv)
  324. m_sign_display = SignDisplay::Always;
  325. else if (sign_display == "exceptZero"sv)
  326. m_sign_display = SignDisplay::ExceptZero;
  327. else if (sign_display == "negative"sv)
  328. m_sign_display = SignDisplay::Negative;
  329. else
  330. VERIFY_NOT_REACHED();
  331. }
  332. StringView NumberFormat::sign_display_string() const
  333. {
  334. switch (m_sign_display) {
  335. case SignDisplay::Auto:
  336. return "auto"sv;
  337. case SignDisplay::Never:
  338. return "never"sv;
  339. case SignDisplay::Always:
  340. return "always"sv;
  341. case SignDisplay::ExceptZero:
  342. return "exceptZero"sv;
  343. case SignDisplay::Negative:
  344. return "negative"sv;
  345. default:
  346. VERIFY_NOT_REACHED();
  347. }
  348. }
  349. // 15.5.1 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  350. int currency_digits(StringView currency)
  351. {
  352. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  353. // unit value corresponding to the currency from the list; otherwise, return 2.
  354. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  355. return currency_code->minor_unit.value_or(2);
  356. return 2;
  357. }
  358. // 15.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  359. FormatResult format_numeric_to_string(NumberFormatBase const& intl_object, MathematicalValue number)
  360. {
  361. bool is_negative = false;
  362. // 1. If x is negative-zero, then
  363. if (number.is_negative_zero()) {
  364. // a. Let isNegative be true.
  365. is_negative = true;
  366. // b. Set x to 0.
  367. number = MathematicalValue(0.0);
  368. }
  369. // 2. Else,
  370. else {
  371. // a. Assert: x is a mathematical value.
  372. VERIFY(number.is_mathematical_value());
  373. // b. If x < 0, let isNegative be true; else let isNegative be false.
  374. is_negative = number.is_negative();
  375. // c. If isNegative is true, then
  376. if (is_negative) {
  377. // i. Set x to -x.
  378. number.negate();
  379. }
  380. }
  381. // 3. Let unsignedRoundingMode be GetUnsignedRoundingMode(intlObject.[[RoundingMode]], isNegative).
  382. auto unsigned_rounding_mode = get_unsigned_rounding_mode(intl_object.rounding_mode(), is_negative);
  383. RawFormatResult result {};
  384. switch (intl_object.rounding_type()) {
  385. // 4. If intlObject.[[RoundingType]] is significantDigits, then
  386. case NumberFormatBase::RoundingType::SignificantDigits:
  387. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  388. result = to_raw_precision(number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode);
  389. break;
  390. // 5. Else if intlObject.[[RoundingType]] is fractionDigits, then
  391. case NumberFormatBase::RoundingType::FractionDigits:
  392. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  393. result = to_raw_fixed(number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode);
  394. break;
  395. // 6. Else,
  396. case NumberFormatBase::RoundingType::MorePrecision:
  397. case NumberFormatBase::RoundingType::LessPrecision: {
  398. // a. Let sResult be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  399. auto significant_result = to_raw_precision(number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode);
  400. // b. Let fResult be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  401. auto fraction_result = to_raw_fixed(number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode);
  402. // c. If intlObj.[[RoundingType]] is morePrecision, then
  403. if (intl_object.rounding_type() == NumberFormatBase::RoundingType::MorePrecision) {
  404. // i. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  405. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  406. // 1. Let result be sResult.
  407. result = move(significant_result);
  408. }
  409. // ii. Else,
  410. else {
  411. // 2. Let result be fResult.
  412. result = move(fraction_result);
  413. }
  414. }
  415. // d. Else,
  416. else {
  417. // i. Assert: intlObj.[[RoundingType]] is lessPrecision.
  418. VERIFY(intl_object.rounding_type() == NumberFormatBase::RoundingType::LessPrecision);
  419. // ii. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  420. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  421. // 1. Let result be fResult.
  422. result = move(fraction_result);
  423. }
  424. // iii. Else,
  425. else {
  426. // 1. Let result be sResult.
  427. result = move(significant_result);
  428. }
  429. }
  430. break;
  431. }
  432. default:
  433. VERIFY_NOT_REACHED();
  434. }
  435. // 7. Set x to result.[[RoundedNumber]].
  436. number = move(result.rounded_number);
  437. // 8. Let string be result.[[FormattedString]].
  438. auto string = move(result.formatted_string);
  439. // 9. If intlObject.[[TrailingZeroDisplay]] is "stripIfInteger" and x modulo 1 = 0, then
  440. if ((intl_object.trailing_zero_display() == NumberFormat::TrailingZeroDisplay::StripIfInteger) && number.modulo_is_zero(1)) {
  441. // a. Let i be StringIndexOf(string, ".", 0).
  442. auto index = string.find_byte_offset('.');
  443. // b. If i ≠ -1, set string to the substring of string from 0 to i.
  444. if (index.has_value())
  445. string = MUST(string.substring_from_byte_offset(0, *index));
  446. }
  447. // 10. Let int be result.[[IntegerDigitsCount]].
  448. int digits = result.digits;
  449. // 11. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  450. int min_integer = intl_object.min_integer_digits();
  451. // 12. If int < minInteger, then
  452. if (digits < min_integer) {
  453. // a. Let forwardZeros be the String consisting of minInteger - int occurrences of the code unit 0x0030 (DIGIT ZERO).
  454. auto forward_zeros = MUST(String::repeated('0', min_integer - digits));
  455. // b. Set string to the string-concatenation of forwardZeros and string.
  456. string = MUST(String::formatted("{}{}", forward_zeros, string));
  457. }
  458. // 13. If isNegative is true, then
  459. if (is_negative) {
  460. // a. If x is 0, set x to negative-zero. Otherwise, set x to -x.
  461. if (number.is_zero())
  462. number = MathematicalValue { MathematicalValue::Symbol::NegativeZero };
  463. else
  464. number.negate();
  465. }
  466. // 14. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  467. return { move(string), move(number) };
  468. }
  469. // 15.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  470. Vector<PatternPartition> partition_number_pattern(VM& vm, NumberFormat& number_format, MathematicalValue number)
  471. {
  472. // 1. Let exponent be 0.
  473. int exponent = 0;
  474. String formatted_string;
  475. // 2. If x is not-a-number, then
  476. if (number.is_nan()) {
  477. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  478. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::NaN).value_or("NaN"sv);
  479. formatted_string = MUST(String::from_utf8(symbol));
  480. }
  481. // 3. Else if x is positive-infinity, then
  482. else if (number.is_positive_infinity()) {
  483. // a. Let n be an ILD String value indicating positive infinity.
  484. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  485. formatted_string = MUST(String::from_utf8(symbol));
  486. }
  487. // 4. Else if x is negative-infinity, then
  488. else if (number.is_negative_infinity()) {
  489. // a. Let n be an ILD String value indicating negative infinity.
  490. // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
  491. // be inserted by the pattern returned from GetNumberFormatPattern.
  492. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  493. formatted_string = MUST(String::from_utf8(symbol));
  494. }
  495. // 5. Else,
  496. else {
  497. // a. If x is not negative-zero,
  498. if (!number.is_negative_zero()) {
  499. // i. Assert: x is a mathematical value.
  500. VERIFY(number.is_mathematical_value());
  501. // ii. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  502. if (number_format.style() == NumberFormat::Style::Percent)
  503. number = number.multiplied_by(100);
  504. // iii. Let exponent be ComputeExponent(numberFormat, x).
  505. exponent = compute_exponent(number_format, number);
  506. // iv. Let x be x × 10^-exponent.
  507. number = number.multiplied_by_power(-exponent);
  508. }
  509. // b. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  510. auto format_number_result = format_numeric_to_string(number_format, move(number));
  511. // c. Let n be formatNumberResult.[[FormattedString]].
  512. formatted_string = move(format_number_result.formatted_string);
  513. // d. Let x be formatNumberResult.[[RoundedNumber]].
  514. number = move(format_number_result.rounded_number);
  515. }
  516. ::Locale::NumberFormat found_pattern {};
  517. // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
  518. auto pattern = get_number_format_pattern(vm, number_format, number, found_pattern);
  519. if (!pattern.has_value())
  520. return {};
  521. // 7. Let result be a new empty List.
  522. Vector<PatternPartition> result;
  523. // 8. Let patternParts be PartitionPattern(pattern).
  524. auto pattern_parts = pattern->visit([](auto const& p) { return partition_pattern(p); });
  525. // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  526. for (auto& pattern_part : pattern_parts) {
  527. // a. Let p be patternPart.[[Type]].
  528. auto part = pattern_part.type;
  529. // b. If p is "literal", then
  530. if (part == "literal"sv) {
  531. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  532. result.append({ "literal"sv, move(pattern_part.value) });
  533. }
  534. // c. Else if p is equal to "number", then
  535. else if (part == "number"sv) {
  536. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  537. auto notation_sub_parts = partition_notation_sub_pattern(number_format, number, formatted_string, exponent);
  538. // ii. Append all elements of notationSubParts to result.
  539. result.extend(move(notation_sub_parts));
  540. }
  541. // d. Else if p is equal to "plusSign", then
  542. else if (part == "plusSign"sv) {
  543. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  544. auto plus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PlusSign).value_or("+"sv);
  545. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  546. result.append({ "plusSign"sv, MUST(String::from_utf8(plus_sign_symbol)) });
  547. }
  548. // e. Else if p is equal to "minusSign", then
  549. else if (part == "minusSign"sv) {
  550. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  551. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  552. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  553. result.append({ "minusSign"sv, MUST(String::from_utf8(minus_sign_symbol)) });
  554. }
  555. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  556. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  557. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  558. auto percent_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PercentSign).value_or("%"sv);
  559. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  560. result.append({ "percentSign"sv, MUST(String::from_utf8(percent_sign_symbol)) });
  561. }
  562. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  563. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  564. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  565. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  566. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  567. VERIFY(identifier_index.has_value());
  568. // i. Let unit be numberFormat.[[Unit]].
  569. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  570. // 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.
  571. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  572. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  573. result.append({ "unit"sv, MUST(String::from_utf8(unit_identifier)) });
  574. }
  575. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  576. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  577. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  578. //
  579. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  580. // currency code during GetNumberFormatPattern so that we do not have to do currency
  581. // display / plurality lookups more than once.
  582. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  583. auto currency = number_format.resolve_currency_display();
  584. result.append({ "currency"sv, MUST(String::from_utf8(currency)) });
  585. }
  586. // l. Else,
  587. else {
  588. // i. Let unknown be an ILND String based on x and p.
  589. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  590. // LibUnicode doesn't generate any "unknown" patterns.
  591. VERIFY_NOT_REACHED();
  592. }
  593. }
  594. // 10. Return result.
  595. return result;
  596. }
  597. static Vector<String> separate_integer_into_groups(::Locale::NumberGroupings const& grouping_sizes, String integer, NumberFormat::UseGrouping use_grouping)
  598. {
  599. auto utf8_integer = integer.code_points();
  600. if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
  601. return { move(integer) };
  602. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  603. switch (use_grouping) {
  604. case NumberFormat::UseGrouping::Min2:
  605. if (utf8_integer.length() < 5)
  606. return { move(integer) };
  607. break;
  608. case NumberFormat::UseGrouping::Auto:
  609. if (index < grouping_sizes.minimum_grouping_digits)
  610. return { move(integer) };
  611. break;
  612. case NumberFormat::UseGrouping::Always:
  613. break;
  614. default:
  615. VERIFY_NOT_REACHED();
  616. }
  617. Vector<String> groups;
  618. auto add_group = [&](size_t index, size_t length) {
  619. length = utf8_integer.unicode_substring_view(index, length).byte_length();
  620. index = utf8_integer.byte_offset_of(index);
  621. auto group = MUST(integer.substring_from_byte_offset_with_shared_superstring(index, length));
  622. groups.prepend(move(group));
  623. };
  624. add_group(index, grouping_sizes.primary_grouping_size);
  625. while (index > grouping_sizes.secondary_grouping_size) {
  626. index -= grouping_sizes.secondary_grouping_size;
  627. add_group(index, grouping_sizes.secondary_grouping_size);
  628. }
  629. if (index > 0)
  630. add_group(0, index);
  631. return groups;
  632. }
  633. // 15.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  634. Vector<PatternPartition> partition_notation_sub_pattern(NumberFormat& number_format, MathematicalValue const& number, String formatted_string, int exponent)
  635. {
  636. // 1. Let result be a new empty List.
  637. Vector<PatternPartition> result;
  638. auto grouping_sizes = ::Locale::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  639. if (!grouping_sizes.has_value())
  640. return {};
  641. // 2. If x is not-a-number, then
  642. if (number.is_nan()) {
  643. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  644. result.append({ "nan"sv, move(formatted_string) });
  645. }
  646. // 3. Else if x is positive-infinity or negative-infinity, then
  647. else if (number.is_positive_infinity() || number.is_negative_infinity()) {
  648. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  649. result.append({ "infinity"sv, move(formatted_string) });
  650. }
  651. // 4. Else,
  652. else {
  653. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  654. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  655. if (!notation_sub_pattern.has_value())
  656. return {};
  657. // b. Let patternParts be PartitionPattern(notationSubPattern).
  658. auto pattern_parts = partition_pattern(*notation_sub_pattern);
  659. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  660. for (auto& pattern_part : pattern_parts) {
  661. // i. Let p be patternPart.[[Type]].
  662. auto part = pattern_part.type;
  663. // ii. If p is "literal", then
  664. if (part == "literal"sv) {
  665. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  666. result.append({ "literal"sv, move(pattern_part.value) });
  667. }
  668. // iii. Else if p is equal to "number", then
  669. else if (part == "number"sv) {
  670. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 14 below, then
  671. // a. Let digits be a List whose elements are the code points specified in the "Digits" column of the matching row in Table 14.
  672. // b. Assert: The length of digits is 10.
  673. // c. Let transliterated be the empty String.
  674. // d. Let len be the length of n.
  675. // e. Let position be 0.
  676. // f. Repeat, while position < len,
  677. // i. Let c be the code unit at index position within n.
  678. // ii. If 0x0030 ≤ c ≤ 0x0039, then
  679. // i. NOTE: c is an ASCII digit.
  680. // ii. Let i be c - 0x0030.
  681. // iii. Set c to CodePointsToString(« digits[i] »).
  682. // iii. Set transliterated to the string-concatenation of transliterated and c.
  683. // iv. Set position to position + 1.
  684. // g. Set n to transliterated.
  685. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  686. formatted_string = ::Locale::replace_digits_for_number_system(number_format.numbering_system(), formatted_string);
  687. // 3. Let decimalSepIndex be StringIndexOf(n, ".", 0).
  688. auto decimal_sep_index = formatted_string.find_byte_offset('.');
  689. String integer;
  690. Optional<String> fraction;
  691. // 4. If decimalSepIndex > 0, then
  692. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  693. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  694. integer = MUST(formatted_string.substring_from_byte_offset_with_shared_superstring(0, *decimal_sep_index));
  695. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  696. fraction = MUST(formatted_string.substring_from_byte_offset_with_shared_superstring(*decimal_sep_index + 1));
  697. }
  698. // 5. Else,
  699. else {
  700. // a. Let integer be n.
  701. integer = move(formatted_string);
  702. // b. Let fraction be undefined.
  703. }
  704. // 6. If the numberFormat.[[UseGrouping]] is false, then
  705. if (number_format.use_grouping() == NumberFormat::UseGrouping::False) {
  706. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  707. result.append({ "integer"sv, move(integer) });
  708. }
  709. // 7. Else,
  710. else {
  711. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  712. auto group_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Group).value_or(","sv);
  713. // 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]].
  714. auto groups = separate_integer_into_groups(*grouping_sizes, move(integer), number_format.use_grouping());
  715. // c. Assert: The number of elements in groups List is greater than 0.
  716. VERIFY(!groups.is_empty());
  717. // d. Repeat, while groups List is not empty,
  718. while (!groups.is_empty()) {
  719. // i. Remove the first element from groups and let integerGroup be the value of that element.
  720. auto integer_group = groups.take_first();
  721. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  722. result.append({ "integer"sv, move(integer_group) });
  723. // iii. If groups List is not empty, then
  724. if (!groups.is_empty()) {
  725. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  726. result.append({ "group"sv, MUST(String::from_utf8(group_sep_symbol)) });
  727. }
  728. }
  729. }
  730. // 8. If fraction is not undefined, then
  731. if (fraction.has_value()) {
  732. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  733. auto decimal_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv);
  734. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  735. result.append({ "decimal"sv, MUST(String::from_utf8(decimal_sep_symbol)) });
  736. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  737. result.append({ "fraction"sv, fraction.release_value() });
  738. }
  739. }
  740. // iv. Else if p is equal to "compactSymbol", then
  741. // v. Else if p is equal to "compactName", then
  742. else if (part.starts_with("compactIdentifier:"sv)) {
  743. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  744. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  745. VERIFY(identifier_index.has_value());
  746. // 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.
  747. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  748. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  749. result.append({ "compact"sv, MUST(String::from_utf8(compact_identifier)) });
  750. }
  751. // vi. Else if p is equal to "scientificSeparator", then
  752. else if (part == "scientificSeparator"sv) {
  753. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  754. auto scientific_separator = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Exponential).value_or("E"sv);
  755. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  756. result.append({ "exponentSeparator"sv, MUST(String::from_utf8(scientific_separator)) });
  757. }
  758. // vii. Else if p is equal to "scientificExponent", then
  759. else if (part == "scientificExponent"sv) {
  760. // 1. If exponent < 0, then
  761. if (exponent < 0) {
  762. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  763. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  764. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  765. result.append({ "exponentMinusSign"sv, MUST(String::from_utf8(minus_sign_symbol)) });
  766. // c. Let exponent be -exponent.
  767. exponent *= -1;
  768. }
  769. // 2. Let exponentResult be ToRawFixed(exponent, 0, 0, 1, undefined).
  770. auto exponent_value = MathematicalValue { static_cast<double>(exponent) };
  771. auto exponent_result = to_raw_fixed(exponent_value, 0, 0, 1, {});
  772. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  773. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  774. exponent_result.formatted_string = ::Locale::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string);
  775. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  776. result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
  777. }
  778. // viii. Else,
  779. else {
  780. // 1. Let unknown be an ILND String based on x and p.
  781. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  782. // LibUnicode doesn't generate any "unknown" patterns.
  783. VERIFY_NOT_REACHED();
  784. }
  785. }
  786. }
  787. // 5. Return result.
  788. return result;
  789. }
  790. // 15.5.6 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  791. String format_numeric(VM& vm, NumberFormat& number_format, MathematicalValue number)
  792. {
  793. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  794. auto parts = partition_number_pattern(vm, number_format, move(number));
  795. // 2. Let result be the empty String.
  796. StringBuilder result;
  797. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  798. for (auto& part : parts) {
  799. // a. Set result to the string-concatenation of result and part.[[Value]].
  800. result.append(part.value);
  801. }
  802. // 4. Return result.
  803. return MUST(result.to_string());
  804. }
  805. // 15.5.7 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  806. NonnullGCPtr<Array> format_numeric_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue number)
  807. {
  808. auto& realm = *vm.current_realm();
  809. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  810. auto parts = partition_number_pattern(vm, number_format, move(number));
  811. // 2. Let result be ! ArrayCreate(0).
  812. auto result = MUST(Array::create(realm, 0));
  813. // 3. Let n be 0.
  814. size_t n = 0;
  815. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  816. for (auto& part : parts) {
  817. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  818. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  819. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  820. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  821. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  822. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  823. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  824. MUST(result->create_data_property_or_throw(n, object));
  825. // e. Increment n by 1.
  826. ++n;
  827. }
  828. // 5. Return result.
  829. return result;
  830. }
  831. static String cut_trailing_zeroes(StringView string, int cut)
  832. {
  833. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  834. // Repeat, while cut > 0 and the last code unit of m is 0x0030 (DIGIT ZERO),
  835. while ((cut > 0) && string.ends_with('0')) {
  836. // Remove the last code unit from m.
  837. string = string.substring_view(0, string.length() - 1);
  838. // Decrease cut by 1.
  839. --cut;
  840. }
  841. // If the last code unit of m is 0x002E (FULL STOP), then
  842. if (string.ends_with('.')) {
  843. // Remove the last code unit from m.
  844. string = string.substring_view(0, string.length() - 1);
  845. }
  846. return MUST(String::from_utf8(string));
  847. }
  848. enum class PreferredResult {
  849. LessThanNumber,
  850. GreaterThanNumber,
  851. };
  852. struct RawPrecisionResult {
  853. MathematicalValue number;
  854. int exponent { 0 };
  855. MathematicalValue rounded;
  856. };
  857. // ToRawPrecisionFn, https://tc39.es/ecma402/#eqn-ToRawPrecisionFn
  858. static RawPrecisionResult to_raw_precision_function(MathematicalValue const& number, int precision, PreferredResult mode)
  859. {
  860. RawPrecisionResult result {};
  861. result.exponent = number.logarithmic_floor();
  862. if (number.is_number()) {
  863. result.number = number.divided_by_power(result.exponent - precision + 1);
  864. switch (mode) {
  865. case PreferredResult::LessThanNumber:
  866. result.number = MathematicalValue { floor(result.number.as_number()) };
  867. break;
  868. case PreferredResult::GreaterThanNumber:
  869. result.number = MathematicalValue { ceil(result.number.as_number()) };
  870. break;
  871. }
  872. } else {
  873. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  874. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  875. result.number = number.divided_by_power(result.exponent - precision);
  876. // FIXME: Can we do this without string conversion?
  877. auto digits = result.number.to_string();
  878. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  879. result.number = result.number.divided_by(10);
  880. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  881. result.number = result.number.plus(1);
  882. }
  883. result.rounded = result.number.multiplied_by_power(result.exponent - precision + 1);
  884. return result;
  885. }
  886. // 15.5.8 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  887. RawFormatResult to_raw_precision(MathematicalValue const& number, int min_precision, int max_precision, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  888. {
  889. RawFormatResult result {};
  890. // 1. Let p be maxPrecision.
  891. int precision = max_precision;
  892. int exponent = 0;
  893. // 2. If x = 0, then
  894. if (number.is_zero()) {
  895. // a. Let m be the String consisting of p occurrences of the code unit 0x0030 (DIGIT ZERO).
  896. result.formatted_string = MUST(String::repeated('0', precision));
  897. // b. Let e be 0.
  898. exponent = 0;
  899. // c. Let xFinal be 0.
  900. result.rounded_number = MathematicalValue { 0.0 };
  901. }
  902. // 3. Else,
  903. else {
  904. // a. Let n1 and e1 each be an integer and r1 a mathematical value, with r1 = ToRawPrecisionFn(n1, e1, p), such that r1 ≤ x and r1 is maximized.
  905. auto [number1, exponent1, rounded1] = to_raw_precision_function(number, precision, PreferredResult::LessThanNumber);
  906. // b. Let n2 and e2 each be an integer and r2 a mathematical value, with r2 = ToRawPrecisionFn(n2, e2, p), such that r2 ≥ x and r2 is minimized.
  907. auto [number2, exponent2, rounded2] = to_raw_precision_function(number, precision, PreferredResult::GreaterThanNumber);
  908. // c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  909. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  910. MathematicalValue n;
  911. // d. If r is r1, then
  912. if (rounded == RoundingDecision::LowerValue) {
  913. // i. Let n be n1.
  914. n = move(number1);
  915. // ii. Let e be e1.
  916. exponent = exponent1;
  917. // iii. Let xFinal be r1.
  918. result.rounded_number = move(rounded1);
  919. }
  920. // e. Else,
  921. else {
  922. // i. Let n be n2.
  923. n = move(number2);
  924. // ii. Let e be e2.
  925. exponent = exponent2;
  926. // iii. Let xFinal be r2.
  927. result.rounded_number = move(rounded2);
  928. }
  929. // f. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  930. result.formatted_string = n.to_string();
  931. }
  932. // 4. If e ≥ (p – 1), then
  933. if (exponent >= (precision - 1)) {
  934. // a. Set m to the string-concatenation of m and e - p + 1 occurrences of the code unit 0x0030 (DIGIT ZERO).
  935. result.formatted_string = MUST(String::formatted(
  936. "{}{}",
  937. result.formatted_string,
  938. MUST(String::repeated('0', exponent - precision + 1))));
  939. // b. Let int be e + 1.
  940. result.digits = exponent + 1;
  941. }
  942. // 5. Else if e ≥ 0, then
  943. else if (exponent >= 0) {
  944. // a. Set m to the string-concatenation of the first e + 1 code units of m, the code unit 0x002E (FULL STOP), and the remaining p - (e + 1) code units of m.
  945. result.formatted_string = MUST(String::formatted(
  946. "{}.{}",
  947. result.formatted_string.bytes_as_string_view().substring_view(0, exponent + 1),
  948. result.formatted_string.bytes_as_string_view().substring_view(exponent + 1)));
  949. // b. Let int be e + 1.
  950. result.digits = exponent + 1;
  951. }
  952. // 6. Else,
  953. else {
  954. // a. Assert: e < 0.
  955. // b. Set m to the string-concatenation of "0.", -(e + 1) occurrences of the code unit 0x0030 (DIGIT ZERO), and m.
  956. result.formatted_string = MUST(String::formatted(
  957. "0.{}{}",
  958. MUST(String::repeated('0', -1 * (exponent + 1))),
  959. result.formatted_string));
  960. // c. Let int be 1.
  961. result.digits = 1;
  962. }
  963. // 7. If m contains the code unit 0x002E (FULL STOP) 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. // 8. 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. struct RawFixedResult {
  975. MathematicalValue number;
  976. MathematicalValue rounded;
  977. };
  978. // ToRawFixedFn, https://tc39.es/ecma402/#eqn-ToRawFixedFn
  979. static RawFixedResult to_raw_fixed_function(MathematicalValue const& number, int fraction, int rounding_increment, PreferredResult mode)
  980. {
  981. RawFixedResult result {};
  982. if (number.is_number()) {
  983. result.number = number.multiplied_by_power(fraction);
  984. switch (mode) {
  985. case PreferredResult::LessThanNumber:
  986. result.number = MathematicalValue { floor(result.number.as_number()) };
  987. break;
  988. case PreferredResult::GreaterThanNumber:
  989. result.number = MathematicalValue { ceil(result.number.as_number()) };
  990. break;
  991. }
  992. } else {
  993. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  994. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  995. result.number = number.multiplied_by_power(fraction - 1);
  996. // FIXME: Can we do this without string conversion?
  997. auto digits = result.number.to_string();
  998. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  999. result.number = result.number.multiplied_by(10);
  1000. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  1001. result.number = result.number.plus(1);
  1002. }
  1003. while (!result.number.modulo_is_zero(rounding_increment)) {
  1004. switch (mode) {
  1005. case PreferredResult::LessThanNumber:
  1006. result.number = result.number.minus(1);
  1007. break;
  1008. case PreferredResult::GreaterThanNumber:
  1009. result.number = result.number.plus(1);
  1010. break;
  1011. }
  1012. }
  1013. result.rounded = result.number.divided_by_power(fraction);
  1014. return result;
  1015. }
  1016. // 15.5.9 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  1017. RawFormatResult to_raw_fixed(MathematicalValue const& number, int min_fraction, int max_fraction, int rounding_increment, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  1018. {
  1019. RawFormatResult result {};
  1020. // 1. Let f be maxFraction.
  1021. int fraction = max_fraction;
  1022. // 2. Let n1 be an integer and r1 a mathematical value, with r1 = ToRawFixedFn(n1, f), such that n1 modulo roundingIncrement = 0, r1 ≤ x, and r1 is maximized.
  1023. auto [number1, rounded1] = to_raw_fixed_function(number, fraction, rounding_increment, PreferredResult::LessThanNumber);
  1024. // 3. Let n2 be an integer and r2 a mathematical value, with r2 = ToRawFixedFn(n2, f), such that n2 modulo roundingIncrement = 0, r2 ≥ x, and r2 is minimized.
  1025. auto [number2, rounded2] = to_raw_fixed_function(number, fraction, rounding_increment, PreferredResult::GreaterThanNumber);
  1026. // 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  1027. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  1028. MathematicalValue n;
  1029. // 5. If r is r1, then
  1030. if (rounded == RoundingDecision::LowerValue) {
  1031. // a. Let n be n1.
  1032. n = move(number1);
  1033. // b. Let xFinal be r1.
  1034. result.rounded_number = move(rounded1);
  1035. }
  1036. // 6. Else,
  1037. else {
  1038. // a. Let n be n2.
  1039. n = move(number2);
  1040. // b. Let xFinal be r2.
  1041. result.rounded_number = move(rounded2);
  1042. }
  1043. // 7. 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).
  1044. result.formatted_string = n.is_zero() ? "0"_string : n.to_string();
  1045. // 8. If f ≠ 0, then
  1046. if (fraction != 0) {
  1047. // a. Let k be the length of m.
  1048. auto decimals = result.formatted_string.bytes_as_string_view().length();
  1049. // b. If k ≤ f, then
  1050. if (decimals <= static_cast<size_t>(fraction)) {
  1051. // i. Let z be the String value consisting of f + 1 - k occurrences of the code unit 0x0030 (DIGIT ZERO).
  1052. auto zeroes = MUST(String::repeated('0', fraction + 1 - decimals));
  1053. // ii. Let m be the string-concatenation of z and m.
  1054. result.formatted_string = MUST(String::formatted("{}{}", zeroes, result.formatted_string));
  1055. // iii. Let k be f + 1.
  1056. decimals = fraction + 1;
  1057. }
  1058. // c. Let a be the first k - f code units of m, and let b be the remaining f code units of m.
  1059. auto a = result.formatted_string.bytes_as_string_view().substring_view(0, decimals - fraction);
  1060. auto b = result.formatted_string.bytes_as_string_view().substring_view(decimals - fraction, fraction);
  1061. // d. Let m be the string-concatenation of a, ".", and b.
  1062. result.formatted_string = MUST(String::formatted("{}.{}", a, b));
  1063. // e. Let int be the length of a.
  1064. result.digits = a.length();
  1065. }
  1066. // 9. Else, let int be the length of m.
  1067. else {
  1068. result.digits = result.formatted_string.bytes_as_string_view().length();
  1069. }
  1070. // 10. Let cut be maxFraction – minFraction.
  1071. int cut = max_fraction - min_fraction;
  1072. // Steps 11-12 are implemented by cut_trailing_zeroes.
  1073. result.formatted_string = cut_trailing_zeroes(result.formatted_string, cut);
  1074. // 13. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: –f }.
  1075. result.rounding_magnitude = -fraction;
  1076. return result;
  1077. }
  1078. enum class NumberCategory {
  1079. NegativeNonZero,
  1080. NegativeZero,
  1081. PositiveNonZero,
  1082. PositiveZero,
  1083. };
  1084. // 15.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  1085. Optional<Variant<StringView, String>> get_number_format_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, ::Locale::NumberFormat& found_pattern)
  1086. {
  1087. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1088. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1089. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1090. // 4. Let patterns be dataLocaleData.[[patterns]].
  1091. // 5. Assert: patterns is a Record (see 15.3.3).
  1092. Optional<::Locale::NumberFormat> patterns;
  1093. // 6. Let style be numberFormat.[[Style]].
  1094. switch (number_format.style()) {
  1095. // 7. If style is "percent", then
  1096. case NumberFormat::Style::Percent:
  1097. // a. Let patterns be patterns.[[percent]].
  1098. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Percent);
  1099. break;
  1100. // 8. Else if style is "unit", then
  1101. case NumberFormat::Style::Unit: {
  1102. // a. Let unit be numberFormat.[[Unit]].
  1103. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1104. // c. Let patterns be patterns.[[unit]].
  1105. // d. If patterns doesn't have a field [[<unit>]], then
  1106. // i. Let unit be "fallback".
  1107. // e. Let patterns be patterns.[[<unit>]].
  1108. // f. Let patterns be patterns.[[<unitDisplay>]].
  1109. auto formats = ::Locale::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display());
  1110. auto plurality = resolve_plural(number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm));
  1111. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality.plural_category; }); it != formats.end())
  1112. patterns = move(*it);
  1113. break;
  1114. }
  1115. // 9. Else if style is "currency", then
  1116. case NumberFormat::Style::Currency:
  1117. // a. Let currency be numberFormat.[[Currency]].
  1118. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1119. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1120. // d. Let patterns be patterns.[[currency]].
  1121. // e. If patterns doesn't have a field [[<currency>]], then
  1122. // i. Let currency be "fallback".
  1123. // f. Let patterns be patterns.[[<currency>]].
  1124. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1125. // h. Let patterns be patterns.[[<currencySign>]].
  1126. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  1127. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  1128. auto formats = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyUnit);
  1129. auto plurality = resolve_plural(number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm));
  1130. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality.plural_category; }); it != formats.end()) {
  1131. patterns = move(*it);
  1132. break;
  1133. }
  1134. }
  1135. switch (number_format.currency_sign()) {
  1136. case NumberFormat::CurrencySign::Standard:
  1137. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Currency);
  1138. break;
  1139. case NumberFormat::CurrencySign::Accounting:
  1140. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Accounting);
  1141. break;
  1142. }
  1143. break;
  1144. // 10. Else,
  1145. case NumberFormat::Style::Decimal:
  1146. // a. Assert: style is "decimal".
  1147. // b. Let patterns be patterns.[[decimal]].
  1148. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Decimal);
  1149. break;
  1150. default:
  1151. VERIFY_NOT_REACHED();
  1152. }
  1153. if (!patterns.has_value())
  1154. return {};
  1155. NumberCategory category;
  1156. // 11. If x is negative-infinity, then
  1157. if (number.is_negative_infinity()) {
  1158. // a. Let category be negative-nonzero.
  1159. category = NumberCategory::NegativeNonZero;
  1160. }
  1161. // 12. Else if x is negative-zero, then
  1162. else if (number.is_negative_zero()) {
  1163. // a. Let category be negative-zero.
  1164. category = NumberCategory::NegativeZero;
  1165. }
  1166. // 13. Else if x is not-a-number, then
  1167. else if (number.is_nan()) {
  1168. // a. Let category be positive-zero.
  1169. category = NumberCategory::PositiveZero;
  1170. }
  1171. // 14. Else if x is positive-infinity, then
  1172. else if (number.is_positive_infinity()) {
  1173. // a. Let category be positive-nonzero.
  1174. category = NumberCategory::PositiveNonZero;
  1175. }
  1176. // 15. Else,
  1177. else {
  1178. // a. Assert: x is a mathematical value.
  1179. VERIFY(number.is_mathematical_value());
  1180. // b. If x < 0, then
  1181. if (number.is_negative()) {
  1182. // i. Let category be negative-nonzero.
  1183. category = NumberCategory::NegativeNonZero;
  1184. }
  1185. // c. Else if x > 0, then
  1186. else if (number.is_positive()) {
  1187. // i. Let category be positive-nonzero.
  1188. category = NumberCategory::PositiveNonZero;
  1189. }
  1190. // d. Else,
  1191. else {
  1192. // i. Let category be positive-zero.
  1193. category = NumberCategory::PositiveZero;
  1194. }
  1195. }
  1196. StringView pattern;
  1197. // 16. Let signDisplay be numberFormat.[[SignDisplay]].
  1198. switch (number_format.sign_display()) {
  1199. // 17. If signDisplay is "never", then
  1200. case NumberFormat::SignDisplay::Never:
  1201. // a. Let pattern be patterns.[[zeroPattern]].
  1202. pattern = patterns->zero_format;
  1203. break;
  1204. // 18. Else if signDisplay is "auto", then
  1205. case NumberFormat::SignDisplay::Auto:
  1206. // a. If category is positive-nonzero or positive-zero, then
  1207. if (category == NumberCategory::PositiveNonZero || category == NumberCategory::PositiveZero) {
  1208. // i. Let pattern be patterns.[[zeroPattern]].
  1209. pattern = patterns->zero_format;
  1210. }
  1211. // b. Else,
  1212. else {
  1213. // i. Let pattern be patterns.[[negativePattern]].
  1214. pattern = patterns->negative_format;
  1215. }
  1216. break;
  1217. // 19. Else if signDisplay is "always", then
  1218. case NumberFormat::SignDisplay::Always:
  1219. // a. If category is positive-nonzero or positive-zero, then
  1220. if (category == NumberCategory::PositiveNonZero || category == NumberCategory::PositiveZero) {
  1221. // i. Let pattern be patterns.[[positivePattern]].
  1222. pattern = patterns->positive_format;
  1223. }
  1224. // b. Else,
  1225. else {
  1226. // i. Let pattern be patterns.[[negativePattern]].
  1227. pattern = patterns->negative_format;
  1228. }
  1229. break;
  1230. // 20. Else if signDisplay is "exceptZero", then
  1231. case NumberFormat::SignDisplay::ExceptZero:
  1232. // a. If category is positive-zero or negative-zero, then
  1233. if (category == NumberCategory::PositiveZero || category == NumberCategory::NegativeZero) {
  1234. // i. Let pattern be patterns.[[zeroPattern]].
  1235. pattern = patterns->zero_format;
  1236. }
  1237. // b. Else if category is positive-nonzero, then
  1238. else if (category == NumberCategory::PositiveNonZero) {
  1239. // i. Let pattern be patterns.[[positivePattern]].
  1240. pattern = patterns->positive_format;
  1241. }
  1242. // c. Else,
  1243. else {
  1244. // i. Let pattern be patterns.[[negativePattern]].
  1245. pattern = patterns->negative_format;
  1246. }
  1247. break;
  1248. // 21. Else,
  1249. case NumberFormat::SignDisplay::Negative:
  1250. // a. Assert: signDisplay is "negative".
  1251. // b. If category is negative-nonzero, then
  1252. if (category == NumberCategory::NegativeNonZero) {
  1253. // i. Let pattern be patterns.[[negativePattern]].
  1254. pattern = patterns->negative_format;
  1255. }
  1256. // c. Else,
  1257. else {
  1258. // i. Let pattern be patterns.[[zeroPattern]].
  1259. pattern = patterns->zero_format;
  1260. }
  1261. break;
  1262. default:
  1263. VERIFY_NOT_REACHED();
  1264. }
  1265. found_pattern = patterns.release_value();
  1266. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  1267. // we might need to mutate the format pattern to inject a space between the currency display and
  1268. // the currency number.
  1269. if (number_format.style() == NumberFormat::Style::Currency) {
  1270. auto modified_pattern = ::Locale::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern);
  1271. if (modified_pattern.has_value())
  1272. return modified_pattern.release_value();
  1273. }
  1274. // 22. Return pattern.
  1275. return pattern;
  1276. }
  1277. // 15.5.12 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1278. Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
  1279. {
  1280. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1281. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1282. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1283. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1284. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1285. // 6. Let notation be numberFormat.[[Notation]].
  1286. auto notation = number_format.notation();
  1287. // 7. If notation is "scientific" or notation is "engineering", then
  1288. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1289. // a. Return notationSubPatterns.[[scientific]].
  1290. auto notation_sub_patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Scientific);
  1291. if (!notation_sub_patterns.has_value())
  1292. return {};
  1293. return notation_sub_patterns->zero_format;
  1294. }
  1295. // 8. Else if exponent is not 0, then
  1296. else if (exponent != 0) {
  1297. // a. Assert: notation is "compact".
  1298. VERIFY(notation == NumberFormat::Notation::Compact);
  1299. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1300. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1301. // d. Return compactPatterns.[[<exponent>]].
  1302. if (number_format.has_compact_format())
  1303. return number_format.compact_format().zero_format;
  1304. }
  1305. // 9. Else,
  1306. // a. Return "{number}".
  1307. return "{number}"sv;
  1308. }
  1309. // 15.5.13 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1310. int compute_exponent(NumberFormat& number_format, MathematicalValue number)
  1311. {
  1312. // 1. If x = 0, then
  1313. if (number.is_zero()) {
  1314. // a. Return 0.
  1315. return 0;
  1316. }
  1317. // 2. If x < 0, then
  1318. if (number.is_negative()) {
  1319. // a. Let x = -x.
  1320. number.negate();
  1321. }
  1322. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1323. int magnitude = number.logarithmic_floor();
  1324. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1325. int exponent = compute_exponent_for_magnitude(number_format, magnitude);
  1326. // 5. Let x be x × 10^(-exponent).
  1327. number = number.multiplied_by_power(-exponent);
  1328. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1329. auto format_number_result = format_numeric_to_string(number_format, move(number));
  1330. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1331. if (format_number_result.rounded_number.is_zero()) {
  1332. // a. Return exponent.
  1333. return exponent;
  1334. }
  1335. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1336. int new_magnitude = format_number_result.rounded_number.logarithmic_floor();
  1337. // 9. If newMagnitude is magnitude - exponent, then
  1338. if (new_magnitude == magnitude - exponent) {
  1339. // a. Return exponent.
  1340. return exponent;
  1341. }
  1342. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1343. return compute_exponent_for_magnitude(number_format, magnitude + 1);
  1344. }
  1345. // 15.5.14 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1346. int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
  1347. {
  1348. // 1. Let notation be numberFormat.[[Notation]].
  1349. switch (number_format.notation()) {
  1350. // 2. If notation is "standard", then
  1351. case NumberFormat::Notation::Standard:
  1352. // a. Return 0.
  1353. return 0;
  1354. // 3. Else if notation is "scientific", then
  1355. case NumberFormat::Notation::Scientific:
  1356. // a. Return magnitude.
  1357. return magnitude;
  1358. // 4. Else if notation is "engineering", then
  1359. case NumberFormat::Notation::Engineering: {
  1360. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1361. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1362. // b. Return thousands × 3.
  1363. return static_cast<int>(thousands) * 3;
  1364. }
  1365. // 5. Else,
  1366. case NumberFormat::Notation::Compact: {
  1367. // a. Assert: notation is "compact".
  1368. VERIFY(number_format.has_compact_display());
  1369. // 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.
  1370. // c. Return exponent.
  1371. auto compact_format_type = number_format.compact_display() == NumberFormat::CompactDisplay::Short || number_format.style() == NumberFormat::Style::Currency
  1372. ? ::Locale::CompactNumberFormatType::DecimalShort
  1373. : ::Locale::CompactNumberFormatType::DecimalLong;
  1374. auto format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), compact_format_type);
  1375. ::Locale::NumberFormat const* best_number_format = nullptr;
  1376. for (auto const& format_rule : format_rules) {
  1377. if (format_rule.magnitude > magnitude)
  1378. break;
  1379. best_number_format = &format_rule;
  1380. }
  1381. if (best_number_format == nullptr)
  1382. return 0;
  1383. number_format.set_compact_format(*best_number_format);
  1384. return best_number_format->exponent;
  1385. }
  1386. default:
  1387. VERIFY_NOT_REACHED();
  1388. }
  1389. }
  1390. // 15.5.16 ToIntlMathematicalValue ( value ), https://tc39.es/ecma402/#sec-tointlmathematicalvalue
  1391. ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value)
  1392. {
  1393. // 1. Let primValue be ? ToPrimitive(value, number).
  1394. auto primitive_value = TRY(value.to_primitive(vm, Value::PreferredType::Number));
  1395. // 2. If Type(primValue) is BigInt, return the mathematical value of primValue.
  1396. if (primitive_value.is_bigint())
  1397. return primitive_value.as_bigint().big_integer();
  1398. // FIXME: The remaining steps are being refactored into a new Runtime Semantic, StringIntlMV.
  1399. // We short-circuit some of these steps to avoid known pitfalls.
  1400. // See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82
  1401. if (!primitive_value.is_string()) {
  1402. auto number = TRY(primitive_value.to_number(vm));
  1403. return number.as_double();
  1404. }
  1405. // 3. If Type(primValue) is String,
  1406. // a. Let str be primValue.
  1407. auto string = primitive_value.as_string().utf8_string();
  1408. // Step 4 handled separately by the FIXME above.
  1409. // 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number.
  1410. // 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1.
  1411. auto mathematical_value = TRY(primitive_value.to_number(vm)).as_double();
  1412. // 7. If mv is 0 and the first non white space code point in str is -, return negative-zero.
  1413. if (mathematical_value == 0.0 && string.bytes_as_string_view().trim_whitespace(TrimMode::Left).starts_with('-'))
  1414. return MathematicalValue::Symbol::NegativeZero;
  1415. // 8. If mv is 10^10000 and str contains Infinity, return positive-infinity.
  1416. if (mathematical_value == pow(10, 10000) && string.contains("Infinity"sv))
  1417. return MathematicalValue::Symbol::PositiveInfinity;
  1418. // 9. If mv is -10^10000 and str contains Infinity, return negative-infinity.
  1419. if (mathematical_value == pow(-10, 10000) && string.contains("Infinity"sv))
  1420. return MathematicalValue::Symbol::NegativeInfinity;
  1421. // 10. Return mv.
  1422. return mathematical_value;
  1423. }
  1424. // 15.5.17 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/ecma402/#sec-getunsignedroundingmode
  1425. NumberFormat::UnsignedRoundingMode get_unsigned_rounding_mode(NumberFormat::RoundingMode rounding_mode, bool is_negative)
  1426. {
  1427. // 1. If isNegative is true, return the specification type in the third column of Table 15 where the first column is roundingMode and the second column is "negative".
  1428. // 2. Else, return the specification type in the third column of Table 15 where the first column is roundingMode and the second column is "positive".
  1429. // Table 15: Conversion from rounding mode to unsigned rounding mode, https://tc39.es/ecma402/#table-intl-unsigned-rounding-modes
  1430. switch (rounding_mode) {
  1431. case NumberFormat::RoundingMode::Ceil:
  1432. return is_negative ? NumberFormat::UnsignedRoundingMode::Zero : NumberFormat::UnsignedRoundingMode::Infinity;
  1433. case NumberFormat::RoundingMode::Floor:
  1434. return is_negative ? NumberFormat::UnsignedRoundingMode::Infinity : NumberFormat::UnsignedRoundingMode::Zero;
  1435. case NumberFormat::RoundingMode::Expand:
  1436. return NumberFormat::UnsignedRoundingMode::Infinity;
  1437. case NumberFormat::RoundingMode::Trunc:
  1438. return NumberFormat::UnsignedRoundingMode::Zero;
  1439. case NumberFormat::RoundingMode::HalfCeil:
  1440. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfZero : NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1441. case NumberFormat::RoundingMode::HalfFloor:
  1442. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfInfinity : NumberFormat::UnsignedRoundingMode::HalfZero;
  1443. case NumberFormat::RoundingMode::HalfExpand:
  1444. return NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1445. case NumberFormat::RoundingMode::HalfTrunc:
  1446. return NumberFormat::UnsignedRoundingMode::HalfZero;
  1447. case NumberFormat::RoundingMode::HalfEven:
  1448. return NumberFormat::UnsignedRoundingMode::HalfEven;
  1449. default:
  1450. VERIFY_NOT_REACHED();
  1451. };
  1452. }
  1453. // 15.5.18 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/ecma402/#sec-applyunsignedroundingmode
  1454. RoundingDecision apply_unsigned_rounding_mode(MathematicalValue const& x, MathematicalValue const& r1, MathematicalValue const& r2, NumberFormat::UnsignedRoundingMode unsigned_rounding_mode)
  1455. {
  1456. // 1. If x is equal to r1, return r1.
  1457. if (x.is_equal_to(r1))
  1458. return RoundingDecision::LowerValue;
  1459. // FIXME: We skip this assertion due floating point inaccuracies. For example, entering "1.2345"
  1460. // in the JS REPL results in "1.234499999999999", and may cause this assertion to fail.
  1461. //
  1462. // This should be resolved when the "Intl mathematical value" is implemented to support
  1463. // arbitrarily precise decimals.
  1464. // https://tc39.es/ecma402/#intl-mathematical-value
  1465. // 2. Assert: r1 < x < r2.
  1466. // 3. Assert: unsignedRoundingMode is not undefined.
  1467. // 4. If unsignedRoundingMode is zero, return r1.
  1468. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Zero)
  1469. return RoundingDecision::LowerValue;
  1470. // 5. If unsignedRoundingMode is infinity, return r2.
  1471. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Infinity)
  1472. return RoundingDecision::HigherValue;
  1473. // 6. Let d1 be x – r1.
  1474. auto d1 = x.minus(r1);
  1475. // 7. Let d2 be r2 – x.
  1476. auto d2 = r2.minus(x);
  1477. // 8. If d1 < d2, return r1.
  1478. if (d1.is_less_than(d2))
  1479. return RoundingDecision::LowerValue;
  1480. // 9. If d2 < d1, return r2.
  1481. if (d2.is_less_than(d1))
  1482. return RoundingDecision::HigherValue;
  1483. // 10. Assert: d1 is equal to d2.
  1484. VERIFY(d1.is_equal_to(d2));
  1485. // 11. If unsignedRoundingMode is half-zero, return r1.
  1486. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfZero)
  1487. return RoundingDecision::LowerValue;
  1488. // 12. If unsignedRoundingMode is half-infinity, return r2.
  1489. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfInfinity)
  1490. return RoundingDecision::HigherValue;
  1491. // 13. Assert: unsignedRoundingMode is half-even.
  1492. VERIFY(unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfEven);
  1493. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  1494. auto cardinality = r1.divided_by(r2.minus(r1));
  1495. // 15. If cardinality is 0, return r1.
  1496. if (cardinality.modulo_is_zero(2))
  1497. return RoundingDecision::LowerValue;
  1498. // 16. Return r2.
  1499. return RoundingDecision::HigherValue;
  1500. }
  1501. // 15.5.19 PartitionNumberRangePattern ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-partitionnumberrangepattern
  1502. ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pattern(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1503. {
  1504. // 1. If x is NaN or y is NaN, throw a RangeError exception.
  1505. if (start.is_nan())
  1506. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "start"sv);
  1507. if (end.is_nan())
  1508. return vm.throw_completion<RangeError>(ErrorType::NumberIsNaN, "end"sv);
  1509. // 2. Let result be a new empty List.
  1510. Vector<PatternPartitionWithSource> result;
  1511. // 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
  1512. auto raw_start_result = partition_number_pattern(vm, number_format, move(start));
  1513. auto start_result = PatternPartitionWithSource::create_from_parent_list(move(raw_start_result));
  1514. // 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
  1515. auto raw_end_result = partition_number_pattern(vm, number_format, move(end));
  1516. auto end_result = PatternPartitionWithSource::create_from_parent_list(move(raw_end_result));
  1517. // 5. If ! FormatNumeric(numberFormat, x) is equal to ! FormatNumeric(numberFormat, y), then
  1518. auto formatted_start = format_numeric(vm, number_format, start);
  1519. auto formatted_end = format_numeric(vm, number_format, end);
  1520. if (formatted_start == formatted_end) {
  1521. // a. Let appxResult be ? FormatApproximately(numberFormat, xResult).
  1522. auto approximate_result = format_approximately(number_format, move(start_result));
  1523. // b. For each r in appxResult, do
  1524. for (auto& result : approximate_result) {
  1525. // i. Set r.[[Source]] to "shared".
  1526. result.source = "shared"sv;
  1527. }
  1528. // c. Return appxResult.
  1529. return approximate_result;
  1530. }
  1531. // 6. For each element r in xResult, do
  1532. result.ensure_capacity(start_result.size());
  1533. for (auto& start_part : start_result) {
  1534. // a. Append a new Record { [[Type]]: r.[[Type]], [[Value]]: r.[[Value]], [[Source]]: "startRange" } as the last element of result.
  1535. PatternPartitionWithSource part;
  1536. part.type = start_part.type;
  1537. part.value = move(start_part.value);
  1538. part.source = "startRange"sv;
  1539. result.unchecked_append(move(part));
  1540. }
  1541. // 7. Let rangeSeparator be an ILND String value used to separate two numbers.
  1542. auto range_separator_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::RangeSeparator).value_or("-"sv);
  1543. auto range_separator = ::Locale::augment_range_pattern(range_separator_symbol, result.last().value, end_result[0].value);
  1544. // 8. Append a new Record { [[Type]]: "literal", [[Value]]: rangeSeparator, [[Source]]: "shared" } element to result.
  1545. PatternPartitionWithSource part;
  1546. part.type = "literal"sv;
  1547. part.value = range_separator.has_value()
  1548. ? range_separator.release_value()
  1549. : MUST(String::from_utf8(range_separator_symbol));
  1550. part.source = "shared"sv;
  1551. result.append(move(part));
  1552. // 9. For each element r in yResult, do
  1553. result.ensure_capacity(result.size() + end_result.size());
  1554. for (auto& end_part : end_result) {
  1555. // a. Append a new Record { [[Type]]: r.[[Type]], [[Value]]: r.[[Value]], [[Source]]: "endRange" } as the last element of result.
  1556. PatternPartitionWithSource part;
  1557. part.type = end_part.type;
  1558. part.value = move(end_part.value);
  1559. part.source = "endRange"sv;
  1560. result.unchecked_append(move(part));
  1561. }
  1562. // 10. Return ! CollapseNumberRange(result).
  1563. return collapse_number_range(move(result));
  1564. }
  1565. // 15.5.20 FormatApproximately ( numberFormat, result ), https://tc39.es/ecma402/#sec-formatapproximately
  1566. Vector<PatternPartitionWithSource> format_approximately(NumberFormat& number_format, Vector<PatternPartitionWithSource> result)
  1567. {
  1568. // 1. Let approximatelySign be an ILND String value used to signify that a number is approximate.
  1569. auto approximately_sign = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::ApproximatelySign);
  1570. // 2. If approximatelySign is not empty, insert a new Record { [[Type]]: "approximatelySign", [[Value]]: approximatelySign } at an ILND index in result. For example, if numberFormat has [[Locale]] "en-US" and [[NumberingSystem]] "latn" and [[Style]] "decimal", the new Record might be inserted before the first element of result.
  1571. if (approximately_sign.has_value() && !approximately_sign->is_empty()) {
  1572. PatternPartitionWithSource partition;
  1573. partition.type = "approximatelySign"sv;
  1574. partition.value = MUST(String::from_utf8(*approximately_sign));
  1575. result.insert_before_matching(move(partition), [](auto const& part) {
  1576. return part.type.is_one_of("integer"sv, "decimal"sv, "plusSign"sv, "minusSign"sv, "percentSign"sv, "currency"sv);
  1577. });
  1578. }
  1579. // 3. Return result.
  1580. return result;
  1581. }
  1582. // 15.5.21 CollapseNumberRange ( result ), https://tc39.es/ecma402/#sec-collapsenumberrange
  1583. Vector<PatternPartitionWithSource> collapse_number_range(Vector<PatternPartitionWithSource> result)
  1584. {
  1585. // Returning result unmodified is guaranteed to be a correct implementation of CollapseNumberRange.
  1586. return result;
  1587. }
  1588. // 15.5.22 FormatNumericRange ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-formatnumericrange
  1589. ThrowCompletionOr<String> format_numeric_range(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1590. {
  1591. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1592. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1593. // 2. Let result be the empty String.
  1594. StringBuilder result;
  1595. // 3. For each part in parts, do
  1596. for (auto& part : parts) {
  1597. // a. Set result to the string-concatenation of result and part.[[Value]].
  1598. result.append(part.value);
  1599. }
  1600. // 4. Return result.
  1601. return MUST(result.to_string());
  1602. }
  1603. // 15.5.23 FormatNumericRangeToParts ( numberFormat, x, y ), https://tc39.es/ecma402/#sec-formatnumericrangetoparts
  1604. ThrowCompletionOr<NonnullGCPtr<Array>> format_numeric_range_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1605. {
  1606. auto& realm = *vm.current_realm();
  1607. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1608. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1609. // 2. Let result be ! ArrayCreate(0).
  1610. auto result = MUST(Array::create(realm, 0));
  1611. // 3. Let n be 0.
  1612. size_t n = 0;
  1613. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  1614. for (auto& part : parts) {
  1615. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  1616. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  1617. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  1618. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  1619. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  1620. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  1621. // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
  1622. MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));
  1623. // e. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  1624. MUST(result->create_data_property_or_throw(n, object));
  1625. // f. Increment n by 1.
  1626. ++n;
  1627. }
  1628. // 5. Return result.
  1629. return result;
  1630. }
  1631. }