NumberFormat.cpp 59 KB

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