NumberFormat.cpp 81 KB

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