NumberFormat.cpp 78 KB

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