NumberFormat.cpp 79 KB

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