NumberFormat.cpp 63 KB

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