NumberFormat.cpp 62 KB

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