NumberFormat.cpp 81 KB

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