NumberFormat.cpp 80 KB

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